Thursday, April 24, 2008

Adventures in F#

Adventure 1: Reversing an integer list

let rec ReverseList (l: int list) =
 match l with
 ¦ H::T -> (ReverseList T) @ [H]
 ¦ [] -> []

The code is quite simple. It does the following:
  1. define a recoursive function (rec keyword) on integer list argument
  2. use pattern matching (match with) on the argument l to decompose l into a head and a tail. The head is the head (first) element of l and tail is the remainder of l.
  3. use this knowledge to call itself recoursively
  4. It is checked whether l consists of a head H and a tail T, if yes, then ReverseList calls itself with T (the list consisting of the tail of l, i.e. l without the head element) and concatenates (@ operator) the result with the list consisting of the headelement ([H])
  5. if the input argument l is the empty list ([]), then ReverseList exits by returning the empty list.


No comments: