Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sublists of list in F#

How to get sublists

[1]; [1; 2]; [1; 2; 3]; ...; [1; 2; 3; ...; n]

from list

[1; 2; 3; ...; n]

by the most idiomatic way? All that I could is:

List.scan (fun acc elem -> elem::acc) [] [1;2;3;4;5]
> val it : int list list =
    [[]; [1]; [2; 1]; [3; 2; 1]; [4; 3; 2; 1]; [5; 4; 3; 2; 1]]

Thanks.

like image 744
Feofilakt Avatar asked Dec 08 '22 23:12

Feofilakt


2 Answers

Your implementation is fine. Here is my alternative:

let source = [1..10]

let counts = [0..source.Length] // Or start at 1 if you don't want to start with an empty list

counts |> List.map (fun count -> source |> List.take count)
like image 171
Foole Avatar answered Dec 31 '22 09:12

Foole


Throwing mine onto the pile, which is maybe a refinement of Foole's answer:

let inits list =
    list |> List.mapi (fun i _ -> List.take (i + 1) list)

mapi is a useful function: You provide it a function which takes the each index and item.

like image 35
TheQuickBrownFox Avatar answered Dec 31 '22 10:12

TheQuickBrownFox