| 1 |
= ForLoops |
| 2 |
|
| 3 |
A `for`-loop is typically used to iterate over a range of consecutive |
| 4 |
integers that denote indices of some sort. For example, in <<OCaml#>> |
| 5 |
a `for`-loop takes either the form |
| 6 |
---- |
| 7 |
for <name> = <lower> to <upper> do <body> done |
| 8 |
---- |
| 9 |
or the form |
| 10 |
---- |
| 11 |
for <name> = <upper> downto <lower> do <body> done |
| 12 |
---- |
| 13 |
|
| 14 |
Some languages provide considerably more flexible `for`-loop or |
| 15 |
`foreach`-constructs. |
| 16 |
|
| 17 |
A bit surprisingly, <<StandardML#,Standard ML>> provides special syntax |
| 18 |
for `while`-loops, but not for `for`-loops. Indeed, in SML, many uses |
| 19 |
of `for`-loops are better expressed using `app`, `foldl`/`foldr`, |
| 20 |
`map` and many other higher-order functions provided by the |
| 21 |
<<BasisLibrary#,Basis Library>> for manipulating lists, vectors and |
| 22 |
arrays. However, the Basis Library does not provide a function for |
| 23 |
iterating over a range of integer values. Fortunately, it is very |
| 24 |
easy to write one. |
| 25 |
|
| 26 |
|
| 27 |
== A fairly simple design |
| 28 |
|
| 29 |
The following implementation imitates both the syntax and semantics of |
| 30 |
the OCaml `for`-loop. |
| 31 |
|
| 32 |
[source,sml] |
| 33 |
---- |
| 34 |
datatype for = to of int * int |
| 35 |
| downto of int * int |
| 36 |
|
| 37 |
infix to downto |
| 38 |
|
| 39 |
val for = |
| 40 |
fn lo to up => |
| 41 |
(fn f => let fun loop lo = if lo > up then () |
| 42 |
else (f lo; loop (lo+1)) |
| 43 |
in loop lo end) |
| 44 |
| up downto lo => |
| 45 |
(fn f => let fun loop up = if up < lo then () |
| 46 |
else (f up; loop (up-1)) |
| 47 |
in loop up end) |
| 48 |
---- |
| 49 |
|
| 50 |
For example, |
| 51 |
|
| 52 |
[source,sml] |
| 53 |
---- |
| 54 |
for (1 to 9) |
| 55 |
(fn i => print (Int.toString i)) |
| 56 |
---- |
| 57 |
|
| 58 |
would print `123456789` and |
| 59 |
|
| 60 |
[source,sml] |
| 61 |
---- |
| 62 |
for (9 downto 1) |
| 63 |
(fn i => print (Int.toString i)) |
| 64 |
---- |
| 65 |
|
| 66 |
would print `987654321`. |
| 67 |
|
| 68 |
Straightforward formatting of nested loops |
| 69 |
|
| 70 |
[source,sml] |
| 71 |
---- |
| 72 |
for (a to b) |
| 73 |
(fn i => |
| 74 |
for (c to d) |
| 75 |
(fn j => |
| 76 |
...)) |
| 77 |
---- |
| 78 |
|
| 79 |
is fairly readable, but tends to cause the body of the loop to be |
| 80 |
indented quite deeply. |
| 81 |
|
| 82 |
|
| 83 |
== Off-by-one |
| 84 |
|
| 85 |
The above design has an annoying feature. In practice, the upper |
| 86 |
bound of the iterated range is almost always excluded and most loops |
| 87 |
would subtract one from the upper bound: |
| 88 |
|
| 89 |
[source,sml] |
| 90 |
---- |
| 91 |
for (0 to n-1) ... |
| 92 |
for (n-1 downto 0) ... |
| 93 |
---- |
| 94 |
|
| 95 |
It is probably better to break convention and exclude the upper bound |
| 96 |
by default, because it leads to more concise code and becomes |
| 97 |
idiomatic with very little practice. The iterator combinators |
| 98 |
described below exclude the upper bound by default. |
| 99 |
|
| 100 |
|
| 101 |
== Iterator combinators |
| 102 |
|
| 103 |
While the simple `for`-function described in the previous section is |
| 104 |
probably good enough for many uses, it is a bit cumbersome when one |
| 105 |
needs to iterate over a Cartesian product. One might also want to |
| 106 |
iterate over more than just consecutive integers. It turns out that |
| 107 |
one can provide a library of iterator combinators that allow one to |
| 108 |
implement iterators more flexibly. |
| 109 |
|
| 110 |
Since the types of the combinators may be a bit difficult to infer |
| 111 |
from their implementations, let's first take a look at a signature of |
| 112 |
the iterator combinator library: |
| 113 |
|
| 114 |
[source,sml] |
| 115 |
---- |
| 116 |
signature ITER = |
| 117 |
sig |
| 118 |
type 'a t = ('a -> unit) -> unit |
| 119 |
|
| 120 |
val return : 'a -> 'a t |
| 121 |
val >>= : 'a t * ('a -> 'b t) -> 'b t |
| 122 |
|
| 123 |
val none : 'a t |
| 124 |
|
| 125 |
val to : int * int -> int t |
| 126 |
val downto : int * int -> int t |
| 127 |
|
| 128 |
val inList : 'a list -> 'a t |
| 129 |
val inVector : 'a vector -> 'a t |
| 130 |
val inArray : 'a array -> 'a t |
| 131 |
|
| 132 |
val using : ('a, 'b) StringCvt.reader -> 'b -> 'a t |
| 133 |
|
| 134 |
val when : 'a t * ('a -> bool) -> 'a t |
| 135 |
val by : 'a t * ('a -> 'b) -> 'b t |
| 136 |
val @@ : 'a t * 'a t -> 'a t |
| 137 |
val ** : 'a t * 'b t -> ('a, 'b) product t |
| 138 |
|
| 139 |
val for : 'a -> 'a |
| 140 |
end |
| 141 |
---- |
| 142 |
|
| 143 |
Several of the above combinators are meant to be used as infix |
| 144 |
operators. Here is a set of suitable infix declarations: |
| 145 |
|
| 146 |
[source,sml] |
| 147 |
---- |
| 148 |
infix 2 to downto |
| 149 |
infix 1 @@ when by |
| 150 |
infix 0 >>= ** |
| 151 |
---- |
| 152 |
|
| 153 |
A few notes are in order: |
| 154 |
|
| 155 |
* The `'a t` type constructor with the `return` and `>>=` operators forms a monad. |
| 156 |
|
| 157 |
* The `to` and `downto` combinators will omit the upper bound of the range. |
| 158 |
|
| 159 |
* `for` is the identity function. It is purely for syntactic sugar and is not strictly required. |
| 160 |
|
| 161 |
* The `@@` combinator produces an iterator for the concatenation of the given iterators. |
| 162 |
|
| 163 |
* The `**` combinator produces an iterator for the Cartesian product of the given iterators. |
| 164 |
** See <<ProductType#>> for the type constructor `('a, 'b) product` used in the type of the iterator produced by `**`. |
| 165 |
|
| 166 |
* The `using` combinator allows one to iterate over slices, streams and many other kinds of sequences. |
| 167 |
|
| 168 |
* `when` is the filtering combinator. The name `when` is inspired by <<OCaml#>>’s guard clauses. |
| 169 |
|
| 170 |
* `by` is the mapping combinator. |
| 171 |
|
| 172 |
The below implementation of the `ITER`-signature makes use of the |
| 173 |
following basic combinators: |
| 174 |
|
| 175 |
[source,sml] |
| 176 |
---- |
| 177 |
fun const x _ = x |
| 178 |
fun flip f x y = f y x |
| 179 |
fun id x = x |
| 180 |
fun opt fno fso = fn NONE => fno () | SOME ? => fso ? |
| 181 |
fun pass x f = f x |
| 182 |
---- |
| 183 |
|
| 184 |
Here is an implementation the `ITER`-signature: |
| 185 |
|
| 186 |
[source,sml] |
| 187 |
---- |
| 188 |
structure Iter :> ITER = |
| 189 |
struct |
| 190 |
type 'a t = ('a -> unit) -> unit |
| 191 |
|
| 192 |
val return = pass |
| 193 |
fun (iA >>= a2iB) f = iA (flip a2iB f) |
| 194 |
|
| 195 |
val none = ignore |
| 196 |
|
| 197 |
fun (l to u) f = let fun `l = if l<u then (f l; `(l+1)) else () in `l end |
| 198 |
fun (u downto l) f = let fun `u = if u>l then (f (u-1); `(u-1)) else () in `u end |
| 199 |
|
| 200 |
fun inList ? = flip List.app ? |
| 201 |
fun inVector ? = flip Vector.app ? |
| 202 |
fun inArray ? = flip Array.app ? |
| 203 |
|
| 204 |
fun using get s f = let fun `s = opt (const ()) (fn (x, s) => (f x; `s)) (get s) in `s end |
| 205 |
|
| 206 |
fun (iA when p) f = iA (fn a => if p a then f a else ()) |
| 207 |
fun (iA by g) f = iA (f o g) |
| 208 |
fun (iA @@ iB) f = (iA f : unit; iB f) |
| 209 |
fun (iA ** iB) f = iA (fn a => iB (fn b => f (a & b))) |
| 210 |
|
| 211 |
val for = id |
| 212 |
end |
| 213 |
---- |
| 214 |
|
| 215 |
Note that some of the above combinators (e.g. `**`) could be expressed |
| 216 |
in terms of the other combinators, most notably `return` and `>>=`. |
| 217 |
Another implementation issue worth mentioning is that `downto` is |
| 218 |
written specifically to avoid computing `l-1`, which could cause an |
| 219 |
`Overflow`. |
| 220 |
|
| 221 |
To use the above combinators the `Iter`-structure needs to be opened |
| 222 |
|
| 223 |
[source,sml] |
| 224 |
---- |
| 225 |
open Iter |
| 226 |
---- |
| 227 |
|
| 228 |
and one usually also wants to declare the infix status of the |
| 229 |
operators as shown earlier. |
| 230 |
|
| 231 |
Here is an example that illustrates some of the features: |
| 232 |
|
| 233 |
[source,sml] |
| 234 |
---- |
| 235 |
for (0 to 10 when (fn x => x mod 3 <> 0) ** inList ["a", "b"] ** 2 downto 1 by real) |
| 236 |
(fn x & y & z => |
| 237 |
print ("("^Int.toString x^", \""^y^"\", "^Real.toString z^")\n")) |
| 238 |
---- |
| 239 |
|
| 240 |
Using the `Iter` combinators one can easily produce more complicated |
| 241 |
iterators. For example, here is an iterator over a "triangle": |
| 242 |
|
| 243 |
[source,sml] |
| 244 |
---- |
| 245 |
fun triangle (l, u) = l to u >>= (fn i => i to u >>= (fn j => return (i, j))) |
| 246 |
---- |