Skip to content

Variable and constant declarations

circular17 edited this page Sep 20, 2023 · 4 revisions

Constant declarations

In Append, constants are immutable values, meaning once they are assigned a value, it cannot be changed. The keyword let precedes a constant declaration.

If the identifier given starts with _ then the variable or constant is private.

A constant is defined by a name, a type (optional) and a value:

  • let _pi = 3.14 has implicit type float and is only visible inside the module.
  • let x float = 10; y float = 7 defines x and y with explicit type float even if supplied values are int.
  • let x/y/z = 0 defines the three identifiers x, y and z to be equal to 0.
  • let a = [1, 2, 3] defines a constant list of integers.
  • let person = {| firstName: "John", var lastName: "Doe" |}: note that even though lastName is a variable within the record, it's immutable due to the constant declaration of person.

Immutable nature

  • Value assignment: x := 5 will result in a compile error since x is a constant and cannot be reassigned.
  • List modifications: similarly, trying to modify a list element, such as a[1] := 4, is not permissible for constant lists.
  • Function Parameters: constants can't be passed as mutable parameters in function calls. Thus, mut person changeName to call the changeName function on person would be flagged during compilation.

Variable declarations

Variables in Append are mutable, allowing their values to be altered post-declaration. The keyword var is used to declare them.

A variable is defined by a name, a type (optional) and value (optional). At least the type or the value must be specified:

  • var age int defines the age variable but not its value.
  • var year = 1996 defines a year implicitly as int and that can be modified.
  • var hello str = [1, 2, 3] won't be compiled because str and list type are not compatible.

Variables can be modified:

  • age := 10 sets the age to 10.
  • year += 1 adds one year.
  • hello[0] := 5 sets the first value of the array (supposing it was properly defined).

Variables can be passed as mutable to functions:

  • mut year addOne supposing the function addOne increments the parameter.
Clone this wiki locally