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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With