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.
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With