Nick
Nick

Reputation: 6588

FSharp Compound List

What's the cleanest & simplest way to create this 'compound' list in F#?

Input:

[ 1; 2; 3; 4; 5 ]

Desired Output:

[ [1]; [1;2]; [1;2;3]; [1,2,3,4]; [1;2;3;4;5] ]

Upvotes: 2

Views: 72

Answers (2)

Gus
Gus

Reputation: 26174

There are many ways but I think this is a clean one:

[1;2;3;4;5]  
    |> List.scan (fun x y -> x @ [y]) [] 
    |> List.tail

using List.scan and finally List.tail to omit the first element which is an empty list.

Upvotes: 4

plinth
plinth

Reputation: 49179

Here's another way interpreting the contents strictly as ints and using list comprehension:

[1; 2; 3; 4; 5] |> List.map(fun n -> [ for i = 1 to n do yield i ])

And you get the same output as above, but if your input is this:

[2; 1; 2] |> List.map(fun n -> [ for i = 1 to n do yield i ])

You get:

[[1; 2]; [1]; [1; 2]]

Which may or may not be what you want.

Upvotes: 1

Related Questions