Is F # List.collect the same as in C # List.SelectMany?

Is List.collect the equivalent of LINQ List.SelectMany?

[1;2;3;4] |> List.collect (fun x -> [x * x]) // [1;4;9;16]

in LINQ

new List<int>() { 1, 2, 3, 4 }
       .SelectMany(x => new List<int>() { x * x }); // 1;4;9;16

Edited by:

A more suitable example

let list1 = [1;2;3;4]
let list2 = [2;4;6]

// [2; 4; 6; 4; 8; 12; 6; 12; 18; 8; 16; 24]
list1 |> List.collect (fun a -> list2 |> List.map (fun b -> a * b)) 

...

var list1 = new List<int>() { 1, 2, 3, 4 };
var list2 = new List<int>() { 2, 4, 6 }

// 2,4,6,4,8,12,6,12,18,8,16,24
list1.SelectMany(a => list2.Select(b => a * b)); 
+6
source share
4 answers

More or less. Direct F # equivalent SelectManywill be Seq.collectthat has a signature:

Seq.collect : ('T -> 'Collection) -> seq<'T> -> seq<'U> (requires 'Collection :> seq<'U>)

seq<'T>is just a type alias IEnumerable<T>.

F # listis a specific set (an immutable list) and therefore is List.collectevaluated strictly.

Also note that the F # listand .NET types are System.Collections.Generic.List<T>not equivalent. System.Collections.Generic.List<T>is a mutable collection and is usually called through a type alias ResizeArray<'T>in F #.

+11

, Enumerable.SelectMany (IEnumerable<T>), List.collect , . , F # , # .

+8

Just wanted to mention that nothing will stop you from using LINQ extension methods directly in F #:

open System.Linq
open System.Collections.Generic
open System

let xs = seq [seq [1;2;3];  seq [4;5;6]] 
xs.SelectMany(fun x -> x ).Select(fun x -> x * x)
// val it: IEnumerable<int> = seq [1; 4; 9; 16; ...]

And for a more idiomatic solution for your specific example in F # 4.1 (although it only works on two lists):

let list1 = [1;2;3;4]
let list2 = [2;4;6]
(list1,list2) ||> List.allPairs |> List.map (fun (a,b) -> a * b)
//val it : int list = [2; 4; 6; 4; 8; 12; 6; 12; 18; 8; 16; 24]
+2
source

List.map is the function you are looking for.

0
source

All Articles