The difference between list.map and list.collect

What is the difference between a card and a collection? below - I can’t tell the difference ..


List.map <'T,' U> Function

Creates a new collection, the elements of which are the results of applying this 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, this function is applied. Combines all results and returns a combined list.

+8
collections f #
source share
3 answers

The difference is that the output list from map is the same length as the input list. For collect list of results may be longer or shorter than the input, since the function you pass returns a list instead of a single element.

More details - compare 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.

+10
source share

Illustration example

Let's say you have a list of lists:

let list = [ [1; 2]; [3; 4]; [5; 6] ]

And the conversion 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 apply the conversion function and the result will be Concatenate , and List.map apply only the conversion function.

+12
source share

Adding to @John's answer, the difference is in the word Concatenates .

Basically, List.collect f xs same as List.concat (List.map f xs) .

+9
source share

All Articles