Brool brool (n.) : a low roar; a deep murmur or humming

Ocaml Quiz

 |  coding

Quick, an Ocaml quiz:

What is the best way to write a summation function?

let sum a = List.fold_left (fun x total -> x+total) 0 a

or

let sum a = List.fold_right (fun x total -> x+total) a 0 let plus1 a = List.map (fun x -> x+1) a

…or…

let plus1 a = List.rev_map (fun x -> x+1) a

Answer: fold_left and rev_map.

Why? Because fold_left and rev_map are tail recursive, and therefore a) faster, b) use less resources, and c) don’t blow up when you pass a large list. Don’t get me started on the fact that the default List.map is implemented as a recursive procedure!

Discussion

Comments are moderated whenever I remember that I have a blog.

bluestorm | 2008-02-03 21:07:58
You can have fun with "partial application", too : let sum = List.fold_left (+) 0
Reply
Add a comment