let rec ReverseList (l: int list) =
match l with
¦ H::T -> (ReverseList T) @ [H]
¦ [] -> []
The code is quite simple. It does the following:
- define a recoursive function (rec keyword) on integer list argument
- 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.
- use this knowledge to call itself recoursively
- 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])
- if the input argument l is the empty list ([]), then ReverseList exits by returning the empty list.
No comments:
Post a Comment