Functions, declarations, and control structures

This page contains descriptions of declaring functions, local declarations, and control structures.

Declaration Syntax

fun id pat1 = exp1
  | id pat2 = exp2
  | ... 
  | id patn = expn;

where exp1, exp2, …, expn all have the same type.

Declaration Examples

The _(underscore) can be used to omit fields in the pattern. As an example look at the following function. It is a function with two parameters a constant and a list, and it multiplies each entry in the list with the constant, returning the result.

fun listMult (c, x::xs) = (c * x)::listMult(c, xs)
  | listMult (_, nil) = nil

To turn a function f (with two parameters) into an infixed operator write:

infix f;

Two additional examples of functions are described under Example declarations.

Local declarations

The let construct permits the declaration of locally-scoped variables within a function definition. In addition, let may be used within a code segment

Syntax

let
   val pat1 = exp1
   val pat2 = exp2
   ...
   val patn = expn
in
   exp
end;

Examples

 
let
   val file_id = TextIO.openOut("/tmp/outputfile.txt")
   val theString = "The transition occurred again.\n"
   val _ = TextIO.output(file_id, theString)
in
   TextIO.closeOut(file_id)
end;

This let statement could be used in a code segment to save a string in a file each time the corresponding transition occurs.

Control structures

Two control structures are available: if-then-else and case.

Syntax

if bool-exp then exp1 else exp2;

where exp1 and exp2 have the same type.

case exp of
     pat1 => exp1
   | pat2 => exp2
   | ...
   | patn => expn;

where exp1, exp2, …, expn all have the same type.

Examples

if x<3
  then "x is less than three"
else "x is greater than or equal three"

This expression checks whether the value bound to x is less than three, and returns an appropriate string as a response.

if x=p
  then 1`e
else 2`e

This expression checks whether the value bound to x is equal to p. If x is equal to p then the expression evaluates to the multi-set consisting of one e, otherwise it returns the multi-set consisting of 2 instances of e.

case day of 
    Mon => "Today is Monday"
  | Tues => "Today is Tuesday"
  | Wed => "Today is Wednesday"
  | Thurs => "Today is Thursday"
  | Fri => "Today is Friday"
  | _ => "It is a weekend day"

This expression returns a string that is dependent on the value that is bound to day, where day has type Day which is an example of an enumerated color set. The underscore _ in the last line indicates that the expression will return the string “It is a weekend day” when day is bound to a value other than Mon, Tues, Wed, Thurs, or Fri, i.e. when day is bound to either Sat or Sun.