ABSTRACT

As you may have noticed, the full notations for associating names with function values and for calling functions are extremely long winded. We have used them so far to emphasize functions as values. We will now consider some simplifications. First of all, a function definition:

val name1 = fn name2 => expression

may be simplified. val is changed to fun, the = and fn are dropped, and => is replaced with = giving:

fun name1 name2 = expression

For example, some of the functions from the previous chapter become:

– fun tax sum = sum*25 div 100; > val tax = fn : int -> int – fun plural word = word^"s"; > val plural = fn : string -> string – fun voter age = age >= 18; > val voter = fn : int -> bool – fun sq (x:int) = x*x; > val sq = fn : int -> int – fun taxdue tax = fn sum => sum*tax div 100; > val taxdue = fn : int -> int -> int

so:

– fun taxdue tax sum = sum*tax div 100; > val taxdue = fn : int -> int -> int

Similarly:

– fun endword ending word = word^ending; > val endword = fn : string -> string -> string – fun doublefunc func (n:int) = 2*func n; > val doublefunc = fn : (int -> int) -> int -> int

Note that fun is a shorthand for an association between a name and an explicit function value using val. The val form must be retained to associate a name and the value of an expression, even when the expression returns a function value. For example:

fun ending = endword "ing"

is incorrect because the expression:

endword "ing"

is not an explicit function value even though it returns one. The correct form is still:

– val ending = endword "ing"; > val ending = fn : string -> string

Function calls may also be simplified by dropping strict bracketing around function expressions. Thus:

((function argument1) argument2) arguments

becomes:

function argument1 argument2 argument3

which is evaluated from left to right. For example:

– endword "jump" "ing"; > "jumping" : string

However, bracketing is essential when a function call or operator expression is an argument to another function. Consider:

sq sq 3

This is interpreted as:

(sq sq) 3

which fails because sq requires an integer rather than a function as its argument. Instead:

– sq (sq 3); > 81 : int

should be used.