Skip to content

Flow of control

Tim Hardcastle edited this page Feb 29, 2024 · 9 revisions

Charm commands have flow of control in a way that Charm functions don't and can't. This is demonstrated in the file examples/flow.ch.

Let's look at the commands in it one at a time.

Commands are sequences of instructions

Unlike a Charm function, which reaches a return value and returns, Charm commands do things, and so can do them one after another.

seq :
    post "It's just one thing ..." to Output()
    post "... after another." to Output()

Conditionals

And so this means that in Imperative Charm one conditional can follow on another:

check :
    5 % 2 == 0 :
        post "5 is even" to Output()
    else :
        post "5 is odd" to Output()
    6 % 2 == 0 :
        post "6 is even" to Output()
    else :
        post "6 is odd" to Output()

It is recommended that every conditional block should end with an else clause. First, for consistency and second because when one conditional block follows on another like this, Charm identifies the end of the first conditional block with the else clause.

ok

If you want one branch of a conditional to do nothing at all, then you should tell it to return ok: e.g. the following rewrite of the check command above will do nothing unless 5 becomes even or 6 becomes odd:

check :
    5 % 2 == 0 :
        post "5 is even" to Output()
    else :
        ok
    6 % 2 == 0 :
        ok
    else :
        post "6 is odd" to Output()

loop and break

Loops in Imperative Charm are deliberately crude. They are initiated by the loop keyword in place of a conditional, and terminated by break. (Or by stop: see the next subsection.)

For example:

demoLoop :
    get number from Random range 1::11
    loop :
        get userInput from Input("Guess my number! > ")
        int userInput == number :
            post "Correct!" to Output()
            break
        else :
            post "Wrong! Guess again!" to Output()

There is a good reason for this. I can currently see no reason to have any kind of loop in Imperative Charm except to alternate between getting some sort of input and returning some sort of output. Everything else could better be done in Functional Charm using iterators.

I am open to extending the language if it turns out that I am wrong. Such changes will be backward-compatible.

stop

The stop instruction stops the service: it has the same effect as if you put hub halt "<service name>" into the REPL.

stopEverything :
    post "Goodnight Las Vegas!" to Output()
    stop

🧿 Pipefish

Clone this wiki locally