Functions | CPN Tools help |
Functions, local declarations, control structures, etc. | CPN ML |
fun id pat1 = exp1 | id pat2 = exp2 | ... | id patn = expn;
where exp1, exp2, ..., expn
all have the same type.
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.
let
construct permits the declaration of locally-scoped variables within a function definition. In addition, let
may be used within a code segment
let val pat1 = exp1 val pat2 = exp2 ……… val patn = expn in exp end;
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.
if-then-else
and case
.
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.
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 colour 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
.