Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between List.iter and List.map function in OCaml

I came across this function : List.map. What I have understood is that List.map takes a function and a list as an argument and transforms each element in the list.

List.iter does something similar (maybe?), For reference see the example below.:

# let f elem =
Printf.printf "I'm looking at element %d now\n" elem in
List.iter f my_list;;
I'm looking at element 1 now
I'm looking at element 2 now
I'm looking at element 3 now
I'm looking at element 4 now
I'm looking at element 5 now
I'm looking at element 6 now
I'm looking at element 7 now
I'm looking at element 8 now
I'm looking at element 9 now
I'm looking at element 10 now
- : unit = ()

Can someone explain the difference between List.map and List.iter?

NOTE: I am new to OCaml and functional programming.

like image 785
vik-y Avatar asked Mar 02 '16 02:03

vik-y


2 Answers

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. I.e., List.iter is for when you just want to call a function that doesn't return anything interesting. In your example, Printf.printf in fact doesn't return an interesting value (it returns ()).

Try the following:

List.map (fun x -> x + 1) [3; 5; 7; 9]
like image 149
Jeffrey Scofield Avatar answered Sep 24 '22 14:09

Jeffrey Scofield


Jeffrey already answered this question fairly thoroughly, but I would like to elaborate on it.

List.map takes a list of one type and puts each of its values through a function one at a time, and populates another list with those results, so running List.map (string_of_int) [1;2;3] is equivalent to the following:

[string_of_int 1; string_of_int 2; string_of_int 3]

List.iter, on the other hand, should be used when you only want the side effects of a function (e.g. let s = ref 0 in List.iter (fun x -> s := !s + x) [1;2;3], or the example you gave in your code).

In summary, use List.map when you'd like to see something done to each element in a list, use List.iter when you'd like to see something done with each element in a list.

like image 44
chrismamo1 Avatar answered Sep 24 '22 14:09

chrismamo1