Oct 25 2006

Ocaml Quiz

Published by tim at 11:32 am under 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

- What is the best way to write this function?

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!

One response so far

One Response to “Ocaml Quiz”

  1. bluestormon 03 Feb 2008 at 2:07 pm

    You can have fun with “partial application”, too :

    let sum = List.fold_left (+) 0

Trackback URI | Comments RSS

Leave a Reply