GIML: Tutorial Five
More Recursive Functions
- Type in and test the following functions, be sure that you understand what each does:
fun index(0, h::t) = h
| index(n, h::t) = index(n-1, t);
fun takeN(0, h::t) = nil
| takeN(n, h::t) = h :: takeN(n-1, t);
fun dropN(0, x) = x
| dropN(n, h::t) = dropN(n-1,t);
- Sorting. The insert function inserts an integer into an ordered list:
fun insert (n:int) nil = [n]
| insert n (h::t) = if (nComplete the definition and test insert. To sort a list we proceed recursively. Sorting the empty list is trivial, sorting a list (h::t) is a matter of inserting h into the sort t
fun sort nil = nil
| sort (h::t) = ...
- Define the function upto:
upto 5 8 = [5,6,7,8]
- The following functions are required in the next diversion
a) The function dropSpace returns a list with leading spaces removed. The function takeSpace returns just the leading spaces.
fun dropSpace nil = nil
| dropSpace(h::t) = if h=" " then dropSpace t else h::t;
fun takeSpace nil = nil
| takeSpace (h::t)= if h=" " then h::takeSpace(t)
else nil;
Test these on exploded strings which start with spaces.
Define the function dropNonSpace and takeNonSpace and use them to define firstWord and butFirstWord such that:
firstWord(explode "One fine day") = "One"
implode(butFirstWord(explode "One fine day")) = "fine day"
Answers