Constants
Sidef implements three kinds of constants: const, define and enum.

const

The common way of declaring constants in Sidef, is by using the const keyword:
1
const pi = 3.14
2
say pi # prints: 3.14
3
#pi = 3 # compile-time error: can't modify non-lvalue constant
Copied!
This kind of constants are created dynamically at run-time, but cannot be changed during the execution of the program.
When declared inside a class or a function, the constant is created and initialized dynamically, as illustrated in the following example:
1
func f(a) {
2
const x = a # created dynamically at each function call
3
return (x + 2)
4
}
5
6
say f(40) #=> 42
7
say f(50) #=> 52
Copied!

define

This keyword will define a compile-time evaluated constant and will point directly to the object at which it evaluated to.
1
define PHI = (1.25.sqrt + 0.5)
2
define IHP = (-(1.25.sqrt - 0.5))
3
4
say (PHI**7 - IHP**7 / PHI-IHP)
Copied!
This type of constants are the most efficient ones.

enum

The enum keyword will automatically declare and assign a list of constants with ascending numeric values (starting from 0):
1
enum |Black, White|
2
say Black # prints: 0
3
say White # prints: 1
Copied!
Alternatively, we have the possibility for specifying an initial value, which will get incremented after each declaration, by calling the method .inc().
1
enum |α="a", β|
2
say α # prints: 'a'
3
say β # prints: 'b'
Copied!
Last modified 1yr ago
Copy link