Defining Functions Form of a function declaration fun






- Slides: 6
Defining Functions Form of a function declaration: fun <identifier> (<parameter list>) = <expression>; Suppose we wish to create a function upper that converts a lower-case letter into the corresponding uppercase letter. We take advantage of the fact the upper = lower – 32: - fun upper(c) = chr(ord(c) - 32); val upper = fn : char -> char - upper(#"a"); val it = #"A" : char
In the preceding example: - fun upper(c) = chr(ord(c) - 32); val upper = fn : char -> char So, in general in ML: fn: <domain type> -> <range type> where: 1. key word fn. 2. A colon. 3. The type of parameter(s), called the domain type. In out example we have a single parameter but we can have int*real*char represent our parameter. 4. The symbol ->. 5. The type of the result of the function, ie range type.
Note: ML uses fn do describe a value that has a function type while fun is used to declare a particular identifier. Consider the following examples: - fun square(x: real) = x*x; val square = fn : real -> real - fun square(x) = x*x; val square = fn : int -> int - fun square(x) = (x: real)*x; val square = fn : real -> real - fun square(x) = x: real * x; std. In: 18. 26 Error: unbound type constructor: x
Consider the following examples and what is true about the precedence of ordinary operations compared to that of a function: - val radius = 4. 0; val radius = 4. 0 : real - pi*square(radius); GC #0. 0. 1. 14: (0 ms) val it = 50. 24 : real - pi * square radius; val it = 50. 24 : real - val x = 3. 0; val x = 3. 0 : real - val y = 4. 0; val y = 4. 0 : real - square x + y; val it = 13. 0 : real -square(x + y) Val it = 49. 0 : real
Functions With More Than One Parameter - fun max 3(a: real, b, c) = (* maximum of three reals *) = if a>b then = if a>c then a = else c = else = if b>c then b = else c; val max 3 = fn : real * real -> real - max 3(2. 0, 4. 0, 3. 0); val it = 4. 0 : real - fun make. List(a, b, c) = a: : b: : c: : nil; val make. List = fn : 'a * 'a -> 'a list - make. List(1, 2, 3); val it = [1, 2, 3] : int list - make. List(1. 0, 2. 0, 3. 0); val it = [1. 0, 2. 0, 3. 0] : real list Note: Comments in the above program.
External Variables Consider the following example: - val x =3; val x = 3 : int - fun addx(a) = a+x; val addx = fn : int -> int - val x = 10; val x = 10 : int - addx(3); val it = 6 : int -