Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reordering match clauses in a recursive function

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.

like image 925
charles Lgn Avatar asked Feb 14 '18 10:02

charles Lgn


1 Answers

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.

like image 145
Étienne Millon Avatar answered Sep 22 '22 03:09

Étienne Millon