ERights Home elang / blocks 
Back to: The 'escape' Expression On to: The 'try' Expressions

The while Expression

As is familiar, this loops. On each iteration it evaluates the condition expression to a boolean. If false, this exits the loop. If true, this evaluates the body-expression and then tries again. Within the body expression, if "break" is called, the loop is exited, and if "continue" is called, this iteration exits, but we go on to the next iteration.

*** I think it is a bad idea to talk about what these things expand into, save it for the appendix. People who care will immediately see how to build a while out of an escape/loop anyway.

The while-expression is defined by expansion:

escape break {
    loop(thunk {
        if (condition-expression) {
            escape continue {
        } else {

Any variable names defined in the condition are visible in the body. If the loop exits because the condition is false, the value of the while-expression is null. If the loop exits because "break" is called with an argument, this argument is the value of the while expression. Putting this together, here's a function for returning the first line of a file that includes a particular substring:

? pragma.syntax("0.8")

? def findFirst(file, substring) :any {
>     def reader := file.textReader()
>     try {
>         while ((def line := reader.readLine()) != null) {
>             if (line.includes(substring)) {
>                 break(line)
>             }
>         }
>     } finally {
>         reader.close()
>     }
> }
# value: <findFirst>
? findFirst(<c:/jabbertest/jabberwocky.txt>, "and")
# value: "\'Twas brillig and the slithy toves "
? findFirst(<c:/jabbertest/jabberwocky.txt>, "foo") == null
# value: true

As we'll see, this and many similar examples are better expressed with E's for-loop.

Unless stated otherwise, all text on this page which is either unattributed or by Mark S. Miller is hereby placed in the public domain.
ERights Home elang / blocks 
Back to: The 'escape' Expression On to: The 'try' Expressions
Download    FAQ    API    Mail Archive    Donate

report bug (including invalid html)

Golden Key Campaign Blue Ribbon Campaign