(* EMULATING "GOTO" statements. Any combination of GOTO and assignment statements - the worst of imperative code! - can be translated into a set of "mutually recursive functions". Two examples are given: *) (* Given integers n1 and n2 A: s := min(n1,n2); l := max(n1,n2); r := l mod s; B: if r <> 0 then begin n1 := r; n2 := s; goto A end else s; *) fun A (n1,n2,r) = let val s = min(n1,n2) val l = max(n1,n2) val r = l mod s in B (s,l,r) end and B (s,l,r) = if r <> 0 then A (r,s,r) else (s,s,s); (* Given x, y, and z as follows x := 0; y:= 0; z:= 0; F: x := x + 1; G: if y < z then goto F else y := x+y; H: if z > 0 then begin z := z-x; goto F else stop; *) fun F (x,y,z) = G(x+1,y,z) and G (x,y,z) = if y 0 then F(x,y,z-x) else (x,y,z); (* Obviously what I have just presented is not "nice". It was not meant to be "nice". However, it was meant to show you that imperative programming is subsumed by functional programming. Also, it was meant to show that we can map from imperative to functional. That is, in an imperative program we have a sequence of statements, and in the functional program we have a sequence of function calls. Note that in the imperative program, when we contine from statement n to the next statement n+1, this is an "implicit" goto n+1. A goto can then be viewed as a call to a function, and a loop can be viewed as mutual recursion. *) (* PS: what is function A, and what is function F? *)