Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f# sequence of running total

Ok, this looks like it should be easy, but I'm just not getting it. If I have a sequence of numbers, how do I generate a new sequence made up of the running totals? eg for a sequence [1;2;3;4], I want to map it to [1;3;6;10]. In a suitably functional way.

like image 720
Aidan Avatar asked Mar 29 '11 21:03

Aidan


2 Answers

Use List.scan:

let runningTotal = List.scan (+) 0 >> List.tail

[1; 2; 3; 4]
|> runningTotal
|> printfn "%A"

Seq.scan-based implementation:

let runningTotal seq' = (Seq.head seq', Seq.skip 1 seq') ||> Seq.scan (+)

{ 1..4 }
|> runningTotal
|> printfn "%A"
like image 184
ildjarn Avatar answered Sep 20 '22 08:09

ildjarn


Another variation using Seq.scan (Seq.skip 1 gets rid of the leading zero):

> {1..4} |> Seq.scan (+) 0 |> Seq.skip 1;;
val it : seq<int> = seq [1; 3; 6; 10]
like image 45
Stephen Swensen Avatar answered Sep 17 '22 08:09

Stephen Swensen