|
From: Brian P. O'H. <br...@cm...> - 2006-10-25 05:15:02
|
> I was wondering if SML can envoke an iterative loop ( i.e while (...) do ...
> od )
Indeed it does. The syntax is
while (expr) do (expr).
For example, suppose that I desire to count from 1 to 10. Then I could do:
let val n = ref 1 in
while (!n <= 10) do
let val () = TextIO.print ((Int.toString (!n)) ^ "\n") in
n := !n + 1
end
end
>
> or are all loops strictly recursive ( gnu ).
There is, of course, nothing wrong with recursion; I have never
actually used while in my sml code. I could the same thing this way:
(* Generate a list of the integers from m to n *)
val intsFromTo = fn (m, n) =>
let val rec intsFromTo' = fn a => fn c =>
if (c < m) then
a
else
intsFromTo' (c :: a) (c - 1)
in
intsFromTo' [] n
end
(* Now print the numbers from 1 to 10 *)
val () = List.app (fn n=> TextIO.print ((Int.toString n) ^ "\n"))
(intsFromTo (1, 10))
Note that these functions should both be made iterative by the
compiler, as they are tail recursive. I prefer to do things like this
the recursive and applicative way because it is more adaptable and
cleaner (no refs), though one might argue that while is more
understandable. I hope that that helps.
-Brian
|