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


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


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 is implemented as a recursive procedure!


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
Add a comment