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

CPN ML identifier
Example declarations

You must be logged in to post a comment.