Folding list of options

Viewed 915

Given a list [Some 1; Some 2; Some 3] I would like an output Some 6 . Given a list [Some 1; None] should yield None.

But I'm finding it a bit more difficult than I had imagined to achieve this in a clean way.

The best I could come up with was this

let someNums = [Some 1; Some 2; Some 3]
someNums 
|> List.reduce (fun st v ->
  Option.bind (fun x ->
    Option.map (fun y -> x + y) st) v )
3 Answers
Related