Skip to content

Flow control

circular17 edited this page Mar 15, 2024 · 5 revisions

Append is designed to make it easy to control the flow of the program and carry data along the way.

Function composition with back pipe

Functions can be composed on the fly using piping mechanism:

  • 12 square \ double would result in 12^2 * 2 = 288 assuming square computes the square and double multiplies by 2.

Conditional branching

An expression can be used for branching:

  • 12 > 10 ? "greater" else "not greater" is a ternary expression that will return "greater"because the conditional expression is true

Pattern matching can be used with any expression:

n
| < 0 -> "Expecting positive number" print
--> "The number is {n}" print

The last line with --> is the default case.

Code blocks

It is possible to define nested code blocks using braces.

  • person wise { print "The person is {.firstName} {.lastName}" } uses the wise keyword to introduce instructions where the dot . directly refers to it, allowing to access its members.

Code blocks are can be introduced with do ... end and optionally specify effects after the with keyword:

do with JSConsole
    "Hello" print
end

Loops

Within loops, the keywords next and break can be used to get to next iteration or stop the loop.

When the data is enumerable, one can use the each keyword to loop over the values. It will loop until the end of the data is reached or if a break or return instruction is encountered.

// here the variable @n is the loop variable.
// suppose no error will happen when enumerating.
0 ..= 9 each @n
    "n = {$n}" print

// compute a sum and handle errors with pattern matching.
// here the item given by the enumerator is matched to handle errors.
fun<T> a T-enum "sum": T | err do
    var result = #T 0
    a each
    | #ok @x -> result += x
    | #err @e -> return e
    result
end

The repeat keyword introduces a potentially infinite loop. It doesn't repeat unless the next keyword is used.

var myEnum int-enum = 5 getNumbersEnum
repeat () myEnum.fetch
| #ok @i -> { "Number {i}" print. next }
--> break // this is redundant
() myEnum.close

The while loop introduces a conditional loop. It repeats until the condition is false or that the break keyword is used.

// enumerate the lines of a file
enum filename "getLines": str with io do
    var file = filename io.openFile
    while file !eof
        yield file readLine
    file close
end

Clone this wiki locally