1 people like it.

Apply Operators to Options

Simple function to apply operators to option types. Applies the operator to each value and returns a new option containing the result. Treats None as the operator's identity element (i.e., ignores it).

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
// combine two options by applying a function to their values
let opSome f (lhs:'a option) (rhs:'a option) : 'a option =
    match lhs, rhs with
        | Some(l), Some(r)
            -> Some(f l r)
        | Some(l), None
            -> Some(l)
        | None, Some(r)
            -> Some(r)
        | _
            -> None

// curry the operator to produce a functions that "add" options of particular types
let addSomeStrings = opSome<string> (+)
let addSomeInts = opSome<int> (+)

// test with two options containing strings
let foo = Some("foo")
let bar = Some("bar")
addSomeStrings foo bar
addSomeStrings foo None
addSomeStrings None bar
addSomeStrings None None

let two = Some(2)
let three = Some(3)
addSomeInts two three
addSomeInts two None
addSomeInts None three
addSomeInts None None

// also works without the curried function
opSome (+) foo bar
opSome (+) foo None
opSome (+) None bar
opSome (+) None None
opSome (+) two three
opSome (+) two None
opSome (+) None three
opSome (+) None None
val opSome : f:('a -> 'a -> 'a) -> lhs:'a option -> rhs:'a option -> 'a option

Full name: Script.opSome
val f : ('a -> 'a -> 'a)
val lhs : 'a option
type 'T option = Option<'T>

Full name: Microsoft.FSharp.Core.option<_>
val rhs : 'a option
union case Option.Some: Value: 'T -> Option<'T>
val l : 'a
val r : 'a
union case Option.None: Option<'T>
val addSomeStrings : (string option -> string option -> string option)

Full name: Script.addSomeStrings
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
val addSomeInts : (int option -> int option -> int option)

Full name: Script.addSomeInts
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
val foo : string option

Full name: Script.foo
val bar : string option

Full name: Script.bar
val two : int option

Full name: Script.two
val three : int option

Full name: Script.three
Raw view Test code New version

More information

Link:http://fssnip.net/ee
Posted:12 years ago
Author:Richard Broida
Tags: operators , generics , options