NEXT ·  UP ·  PREVIOUS ·  CONTENTS ·  INDEX

Iteration

A natural companion for assignment and sequential composition is an iteration mechanism. It is not essential since any expression which uses an iterative expression could be reformulated as a recursive function. The general form of a loop in Standard ML is the reserved word while followed by a boolean expression involving a pointer (or other counter) followed by the word do followed by an expression which performs some computation, changing the state and advancing the pointer.

As an example of the use of references and the while loop we will supply an imperative version of the factorial function.

fun ifac N =
  let
    val n = ref N and i = ref 1
  in 
    while !n <> 0 do
       (i := !i * !n; n := !n -1);
    !i
  end;

The function ifac has type int -> int just as the function fac has. Given just the type of a Standard ML function, there is no systematic method which can determine whether the function will ever cause a change to the program state.

Exercise

The while loop is a derived form. Can you work out how it is defined?

NEXT ·  UP ·  PREVIOUS ·  CONTENTS ·  INDEX