5 people like it.

Working from options

Adding together Option types

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
// Option 1: binds
// Not much different to your solution, but slightly less repetitive
let (+.) x y =
    Option.bind (fun x' -> Option.bind (fun y' -> Some (x' + y')) y) x

(Some 10) +. (Some 20)

[
    Some 10
    Some 5
    Some 6
]
|> List.reduce (+.)

// Option 2: With maybe monad from Fsharpx
open FSharpx.Option

let (+..) x y =
    maybe {
        let! x' = x
        let! y' = y
        return x' + y'
    }
val x : int option
val y : int option
module Option

from Microsoft.FSharp.Core
val bind : binder:('T -> 'U option) -> option:'T option -> 'U option

Full name: Microsoft.FSharp.Core.Option.bind
val x' : int
val y' : int
union case Option.Some: Value: 'T -> Option<'T>
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val reduce : reduction:('T -> 'T -> 'T) -> list:'T list -> 'T

Full name: Microsoft.FSharp.Collections.List.reduce
namespace FSharpx
module Option

from FSharpx
val maybe : MaybeBuilder

Full name: FSharpx.Option.maybe
Raw view New version

More information

Link:http://fssnip.net/p9
Posted:2 years ago
Author:mavnn
Tags: option , fsharpx