Skip to content

Procedural programming

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

Control flow

for loops

For loops are expressed as such:

for x in xs do
    ... use 'x' ...

Where x will be an element of the iterable (e.g. array or product) value xs.

Example:

for i in [99..1] do
    iStr = (Conv.to String) i
    jStr = (Conv.to String) (i - 1)
    IO.outln (iStr ++ " bottles of beer on the wall, " ++ iStr " bottles of beer.")
    IO.outln ("Take one down, pass it around, " ++ jStr ++ " bottles of beer on the wall...")

IO.outln "No more bottles of beer on the wall, no more bottles of beer."
IO.outln "Go to the store and buy some more, 99 bottles of beer on the wall..."

while loops

While loops are expressed as:

while x do
    ... use 'x' ...

where x is some expression convertible to Bool.

Example:

numBullets  = 5
standGround = true

while (numBullets > 0) && standGround do
    IO.outln "The invaders are approaching!"
    IO.out "Do you stand your ground and fire? (y/?) "
    ans = IO.inln ()
    if (Chars.toLower ans) == "y" then
        numBullets <- numBullets - 1
        IO.outln "*Bang*"
        if numBullets == 0 then
            IO.outln "Oh no, you're out of bullets!"
    else
        standGround <- false

IO.outln "Good lord, the invaders have reach... Argh!"

Early return

Returning from a function early is expressed using the => operator.

doLoop(x) =
    y = x
    for i in [1..20] do
        if i >= x then
            => x
        else
            y <- x - 1
    y 

Clone this wiki locally