> Seq.scan (fun acc n -> acc + n) 0 [1;2;3;4];; val it : seq<int> = seq [0; 1; 3; 6; ...]
With lists:
> [1;2;3;4] |> List.scan (fun acc n -> acc + n) 0 |> List.tail;; val it : int list = [1; 3; 6; 10]
Edit: Another way with sequences:
let sum s = seq { let x = ref 0 for i in s do x := !x + i yield !x }
Yes, there is a mutable variable, but I consider it more readable (if you want to get rid of the leading 0).
Laurent
source share