List.collect<'T,'U> Function (F#)

Switch View :
ScriptFree
Visual Studio 2010 - Visual F#
List.collect<'T,'U> Function (F#)

Updated: May 2010

For each element of the list, applies the given function. Concatenates all the results and returns the combined list.

Namespace/Module Path: Microsoft.FSharp.Collections.List

Assembly: FSharp.Core (in FSharp.Core.dll)

// Signature:
List.collect : ('T -> 'U list) -> 'T list -> 'U list

// Usage:
List.collect mapping list
Parameters

mapping

Type: 'T -> 'U list

The function to transform each input element into a sublist to be concatenated.

list

Type: 'T list

The input list.

Return Value

The concatenation of the resulting sublists.

Remarks

This function is named Collect in compiled assemblies. If you are accessing the function from a .NET language other than F#, or through reflection, use this name.

Example

The following code example illustrates the use of List.collect.

F#

let list1 = [10; 20; 30]
let collectList = List.collect (fun x -> [for i in 1..3 -> x * i]) list1
printfn "%A" collectList


Output

[1; 2; 3; 2; 4; 6; 3; 6; 9]
Platforms

Windows 7, Windows Vista SP2, Windows XP SP3, Windows XP x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2

Version Information

F# Runtime

Supported in: 2.0, 4.0

Silverlight

Supported in: 3

See Also

Reference

Change History

Date

History

Reason

May 2010

Added code example.

Information enhancement.

Community Content

Nyi Nyi Thann
Flattening a list of lists into just a list using List.collect
We can also flatten a list of lists into a list by using List.collect.
[[1..10];[11..20];[21..30]]  |> List.collect (fun x -> [for i in x -> i])
Output : [1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 20; 21;
   22; 23; 24; 25; 26; 27; 28; 29; 30]  
 By using List.concat, we can also get the same result.
[[1..10];[11..20];[21..30]] |> List.concat;;

Nyi Nyi Thann
Output Error
let list1 = [10; 20; 30]
let collectList = List.collect (fun x -> [for i in 1..3 -> x * i]) list1
printfn "%A" collectList;;

The output of above sample code should be [10; 20; 30; 20; 40; 60; 30; 60; 90].