I am looking at an algorithm to reverse a list in Ocaml:
let rec reverseList list revList=
match list with
| [] -> revList
| h::t -> reverseList t revList@[h]
An example of use would be:
let list = [1;2;3;4];;
reverseList list [];;
And I am wondering why this works. To my understanding, if we reversed list as defined above, we would be looking at the function calls:
reverseList [1;2;3;4] []
reverseList [2;3;4] [1]
reverseList [3;4] [1;2]
reverseList [4] [1;2;3]
reverseList [] [1;2;3;4]
which would return [1;2;3;4]. However, this code works. So why does it work, and why isn't the last line
| h::t -> reverseList t [h]@revList
I have an inkling it has something to do with currying, but I don't understand it that well. Please help!
The expression:
reverseList t revList@[h]
Is parsed like this:
(reverseList t revlist) @ [h]
In other words, it first reverses the tail recursively, then adds the new element to the end. This does in fact work (though it's not an effective way to reverse the list.)
Also note that the revList
parameter is never anything other than an empty list.