Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a let in OCaml's List.map?

In OCaml 3.12.1, List.map is written as follows:

let rec map f = function
    [] -> []
  | a::l -> let r = f a in r :: map f l

I'd expect that last line to be written as | a::l -> f a :: map f l, but instead, there is a seemingly useless let binding. Why?

like image 454
Dog Avatar asked Apr 20 '13 20:04

Dog


People also ask

What does list map do in OCaml?

List. map returns a new list formed from the results of calling the supplied function. List. iter just returns () , which is a specifically uninteresting value.

How do I remove an item from an OCaml list?

Lists in OCaml are immutable. So you can't remove things from them. You normally create another list that doesn't have the things you don't want. For this, you would use List.

What does :: mean in OCaml?

:: means 2 camel humps, ' means 1 hump!

What does list Fold_left do in OCaml?

So fold_left is "folding in" elements of the list from the left to the right, combining each new element using the operator.


1 Answers

I believe it is there to guarantee an order of function application for the map. The order of evaluation of simple expressions in OCaml is unspecified, so without the let the order of applications of f to the elements of the list would be unspecified. Since OCaml is not a pure language, you really would like the order to be specified (f is called on the head of the list first, and so on recursively).

like image 108
Jeffrey Scofield Avatar answered Sep 21 '22 21:09

Jeffrey Scofield