I have some Ocaml courses at school, and for an exercise we must write the function length.
My teacher showed us how Xavier Leroy wrote his function :
let rec length_aux len = function
[] -> len
| a::l -> length_aux (len + 1) l
let length l = length_aux 0 l
When my teacher explained us why he do the length function like that, he said he didn't know why Xavier Leroy didn't write:
let rec length_aux len = function
a::l -> length_aux (len + 1) l
| [] -> len
let length l = length_aux 0 l
... in order to make it faster (since most of the cases the list in nonempty).
So if someone knows why the second one is no better than the first one, could you answer me please ?
Thank you.
For OCaml, this is the same function. The pattern matching will be compiled to a test on whether the list is empty or not, and jump to a side or the other.
Similar code in C would be reordering cases in a switch
statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With