brool

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

Ocaml Quiz

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 to “Ocaml Quiz”

  1. bluestorm ()

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

    let sum = List.fold_left (+) 0

Leave a Reply