ERights Home elang / blocks 
Back to: The 'switch' Expression On to: Iterating by Key-Value Pairs

The for Loop


Iterating by Values

for  value-pattern in  collection-expr  {
     body-expr
}

E's for loop should be familiar at least to Python, Perl, and csh programmers. You can use the for loop to iterate over the values contained in anything E considers to be a collection. In each successive iteration, the value-pattern is matched against a successive value from the collection. The body-expr is evaluated once each time the match succeeds. Any variable names defined by the value-pattern are visible in the body-expr.

Typically, the value-pattern will simply be a single variable name; in this case the match always succeeds, and each iteration runs with this variable defined to hold each value from the collection in turn:

? pragma.syntax("0.8")

? def average(samples) :any {
>     var sum := 0
>     for value in samples {
>         sum += value
>     }
>     sum / samples.size()
> }
# value: <average>

? average([1, 3, 5, 100, 6])
# value: 23.0

In this example, the collection is a ConstList constructed by the square bracket expression in the call to average.

In E, a ConstList is an immutable list of values. E considers a variety of other objects to be collections as well, and all collections can be treated as containing key-value pairs. (In the case of a list, the keys are the indices of the elements, starting at zero and counting upward.) The unabbreviated form of the for loop has both a key-pattern and a value-pattern, as we shall see in the next section.

 
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 'switch' Expression On to: Iterating by Key-Value Pairs
Download    FAQ    API    Mail Archive    Donate

report bug (including invalid html)

Golden Key Campaign Blue Ribbon Campaign