GIML: Tutorial Eight

Accumulating parameters

  1. Here are two common definitions for rev. The obvious definition: fun revobv nil = nil | revobv(h::t)= (revobv t)@[h]; and the obscure definition fun revobs l = let fun r(nil,acc) = acc | r(h::t,acc)= r(t,h::acc) in r(l,nil) end; Try both definitions on some large lists (several thousand items) to determine which is most efficient.
  2. The function countrep count consecutive repetitions of items and returns an item*int tuple list. e.g. countrep ["a","a","b","c","c","c"] = [("a",2),("b",1),("c",3)] Use the function cr with accumulating parameters c (for the current character) and cn (current character count) to define countrep fun cr c cn nil = [(c,cn)] | cr c cn (h::t) = if c=h then ... else (c,cn):: ...
  3. Averages. To calculate the mean of a list, sum the list and divide by the number of elements. To find the median take the middle element of the sorted list. For an even sized list take the mean of the middle two. The mode of a list is the most frequently occurring item. e.g. mean [1,3,3,5,6,6,6] = (1+3+3+5+6+6+6) div 7 = 4 median [1,3,3,5,6,6,6] = 5 mode [1,3,3,5,6,6,6] = 6 Given that the list is in order, each of these may be calculated in one pass using accumulating parameters.