Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between list.map and list.collect

Tags:

collections

f#

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.

like image 452
Carlo V. Dango Avatar asked Sep 14 '13 11:09

Carlo V. Dango


People also ask

What is difference between map and collection?

Collection includes Lists, Sets and Maps. A map is a list of key-value pairs.

What is difference between collection and list?

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.

What is the difference between Set and map in collections framework?

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.


3 Answers

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.

like image 179
John Palmer Avatar answered Oct 14 '22 07:10

John Palmer


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.

like image 21
polkduran Avatar answered Oct 14 '22 08:10

polkduran


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).

like image 41
MisterMetaphor Avatar answered Oct 14 '22 06:10

MisterMetaphor