NEXT ·  UP ·  PREVIOUS ·  CONTENTS ·  INDEX

The takewhile function

The base case for this function occurs when the list is empty. If it is not then there are two sub-cases.

  1. The head element satisfies the predicate.
  2. The head element does not satisfy the predicate.
If the former, the element is retained and the tail searched for other satisfactory elements. If the latter, the selection is over.

fun takewhile (p, []) = []
  | takewhile (p, h::t) =
    if p h then h :: takewhile (p, t) else [];

Exercise

Construct the analogous dropwhile function.

Exercise

Construct a filter function which returns all the elements of a list which satisfy a given predicate.

NEXT ·  UP ·  PREVIOUS ·  CONTENTS ·  INDEX