Exercise #2

Building simple functions

The previous exercise introduced fun declarations for functions. Functions declared in this fashion can be recursive. In this exercise, we will implement some simple recursive functions.

SML allows an external file to be read in through the function use : string -> unit; this will act as if all contents of the file had been typed in by hand. You may want to use this function to ease your work.

  1. Standard ML has an if...then...else... expression. Try to figure out how it works, and which types it requires. Also test whether the else branch can be omitted.
  2. Recall the use of lists from the previous exercise. Standard ML provides several functions to deal with them; two of them are hd and tl. Determine what these do.
  3. For the next task, you will need a list of elements to test on. Introduce a name with a list as its value by using val <name> = <value>;.
  4. Comparison in SML is implemented using the infix operator (=). The empty list can be expressed either as [] or as nil. Using this information, implement a function find0 which searches for the first 0 in a list of integers (the type of such a list is int list) and returns its offset, if found, or the length of the list, if not found. Note: As you have no for or while constructions in SML, you will have to use recursion to achieve the same effect.
Standard ML is installed at /tools/cs/smlnj/bin/sml on the CSEL machines.
Copyright (C) 2003 Programming Languages group, University of Colorado
Christoph Reichenbach, reichenb (at) colorado.edu