Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

f#

Are the List.collect 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:

More appropriate 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)); 
like image 799
giokoguashvili Avatar asked Jul 17 '17 16:07

giokoguashvili


People also ask

What IS F in horsepower?

Lexus IS-F Arrives Next Year With 400 Hp.

Is the F 5 a V8?

Known internally as the 2UR-GSE, the naturally aspirated 5.0-litre V8 engine installed in the Lexus IS F was co-engineered with Yamaha. It was developed as a high-performance derivative of the 32-valve, quad-camshaft UR-series engine range found in the fourth-generation LS 460 and LS 600h.


2 Answers

More or less. The direct F# equivalent to SelectMany would be Seq.collect which has the signature:

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

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

F# list is a concrete collection (an immutable list) and consequently List.collect is evaluated strictly.

Note also that F# list and the .NET System.Collections.Generic.List<T> types are not equivalent. System.Collections.Generic.List<T> is a mutable collection and is normally referred to via its type alias ResizeArray<'T> in F#.

like image 149
TheInnerLight Avatar answered Nov 04 '22 06:11

TheInnerLight


They behave the same however Enumerable.SelectMany returns a lazy sequence (IEnumerable<T>) while List.collect returns a list which is created strictly. Also be aware that F# lists are persistent linked lists while C# lists are backed by an array.

like image 22
Lee Avatar answered Nov 04 '22 08:11

Lee