Skip to content

Variables

Keith Hammond edited this page Apr 12, 2020 · 5 revisions

Variables in Lemni come in 2 flavours: bindings and parameters.

Bindings are lexically scoped names given to values that may be re-bound to other values. Parameters are names bound to arguments of a function that can not be modified or re-bound throughout the duration of the function.

Rebinding and mutating

Rebinding

Names may be rebound and will keep their binding for the duration of their lexical scope. To illustrate this have a look at the following examples:

IO   = import "IO"
Conv = import "Conv"

toStr(x) = (Conv.to String) x

f(x) = 2 * x

g(x) = x * x

main() =
    a = 1
    b = f a // b now set to 2
    a = g b // a now set to 4

    if a > 3 then
        b = a + 1 // new 'b' binding in this scope
        IO.outln (toStr (f b)) // will output 10

    IO.outln (toStr (f b)) // will output 4 as 'b' is not effected in this scope

Mutating

Name bindings may be modified/mutated within their scope. This mutation will mark a function as impure and may disable some optimizations but allows for some techniques that may not be achievable otherwise. An example of mutation:

IO    = import "IO"
Conv  = import "Conv"
Parse = import "Parse"

toStr(i) = (Conv.to String) i

toInt(s) = (Parse.to Int) s // returns Maybe Int

prompt(msg: String) =
    IO.out msg
    IO.inln ()

promptInt(msg: String) =
    v = prompt msg

    try i in (toInt v) then
        i
    else
        IO.outln "Invalid integer"
        promptInt msg

sums(n) =
    sum = 0

    for i in [1..n] do
        val = promptInt "Enter an integer: "
        sum <- sum + val // mutate 'sum'

    sum

main() =
    n   = promptInt "How many integers to sum? "
    sum = sums n
    IO.outln ("Sum = " ++ (toStr sum))

Clone this wiki locally