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
orlet sum a = List.fold_right (fun x total -> x+total) a 0
…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!
Comments are moderated whenever I remember that I have a blog.