What is the difference between map and collect? documentation below - i cant tell the difference..
List.map<'T,'U> Function
Creates a new collection whose elements are the results of applying the given function to each of the elements of the collection.
// Signature: List.map : ('T -> 'U) -> 'T list -> 'U list
List.collect<'T,'U> Function
For each element of the list, applies the given function. Concatenates all the results and returns the combined list.
Collection includes Lists, Sets and Maps. A map is a list of key-value pairs.
In List, data is in particular order. In Set, it can not contain the same data twice. In Collection, it just stores data with no particular order and can contain duplicate data.
The main difference between Set and Map is that Set is unordered and contains different elements, whereas Map contains the data in the key-value pair.
The difference is that the output list from map
is the same length as the input list. For collect
, the output list may be longer or shorter than the input as the function you pass returns a list instead of a single element.
For more detail - compare the signatures. For map
List.map : ('T -> 'U) -> 'T list -> 'U list
and collect
List.collect : ('T -> 'U list) -> 'T list -> 'U list
you can see here that the return type of the function argument is different.
An example for illustration
Let's say you have a list of lists:
let list = [ [1; 2]; [3; 4]; [5; 6] ]
And a transformation function:
let trans = fun x -> [for i in x -> i*10]
List.map trans list
will produce:
[[10; 20]; [30; 40]; [50; 60]]
While
List.collect trans list
will produce:
[10; 20; 30; 40; 50; 60]
List.collect
will apply the transformation function and will Concatenate
the result while List.map
will only apply the transformation function.
Adding to @John's answer, the difference is in the word Concatenates
.
Basically, List.collect f xs
is the same as List.concat (List.map f xs)
.
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