(*
 * This file has the defintion of a general while-loop, using the same basic
 * strategy as is used in the for-loop functions defined in ./for.ml, q.q.v.
 * Note that we must name our version of while to be "while1", since "while"
 * is a reserved word in SML.
 *)

fun while1(test:'x->bool, vars:'x, body:'x->'x): ('x) list =
    if test(vars) then
	let
	    val result = body(vars)
	in
	    while1(test, result, body) @ [result]
	end
    else
	[];


(*
 * Some while loop examples.
 *)
while1 (fn(x,y)=>(x<y), (1, 10), fn(x, y)=>
    let
	val x = x + 1;
    in
	print(x-1);
	print("\n");
	(x,y)
    end
);

fun less(x:int,y) = x<y;
fun body1(x:int,y) =
    let
        val x = x + 1;
    in
	print(x-1);
	print("\n");
        (x,y)
    end;
val initxy = (1,10);
while1(less, initxy, body1) ;