GIML: Tutorial Three: Hints
In creating recursive functions of this sort you must give two equations.
The first is the base equation; for this we specify the value of the
function
at some fixed value of the parameter, often 0 or 1.
The left hand side of the equation has the actual value 0 or 1 in place
of the parameter, the right hand side of the = has the output required
of the function at that value.
The recursive equation typically tells the
system how to construct the n case from the n-1 case. On
the left of the recursive equation we have n as the parameter, on
the right hand side the function will appear within some expression
however the call will be made to the function at n-1 rather
than n.
fun sumto 0 = 0
| sumto n = n + sumto(n-1);
fun listfrom 0 = []
| listfrom n = n::listfrom(n-1);
fun strcopy(s, 0) = ""
| strcopy(s, n) = s ^ strcopy(s,n-1);
Common mistakes include:
- Getting the type of the base case wrong.
People often put 0 on the right hand side of the base case when they mean
nil and vise versa. Think about the type of the output, if the result of
the function should be a list then nil is commonly the base result. If
the output is a number then the base case will be a number.
Errors like this will be caught by the ML type checker - this gives
difficult error messages however they may be of some help, typically it
will say something like
expected: int -> 'Z list
found: int -> int
This means that one of the equations implies that the output should
be a list but other equation implies the output should be an integer.
- People try to perform operations within the functions. Remember you
can only describe the output on the right hand side you are not writing
instructions for the machine to carry out as you would in a traditional
language.
- Missing parameters in the recursive call. If you are defining an
function with two parameters then the function must have the parameters
given explicitly wherever it appears, in all equations, on both the
left and the right of the = sign.
Now go back and try the rest of the problems before getting the rest of
the answers from here.