0 people like it.

Boolean to optional mappings

A small set of operators for converting boolean expressions to an optional type on the principle of false -> None, true -> Some value.

 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: 
// simple mapping
let inline (&=>) condition value = if condition then Some(value) else None
false &=> 2
true &=> 2

// lazy mapping
let inline (%=>) condition (value:Lazy<'T>) = if condition then Some(value.Force()) else None
false %=> lazy(1+1)
true %=> lazy(1+1)

// binding
let inline (@=>) condition value = if condition then value else None
false @=> Some 2
true @=> Some 2

// async mapping
let inline (!=>) condition value = if condition then async{let! a = value in return Some a} else async{return None}
async{
    return! false !=> async {return 2}
} |> Async.RunSynchronously
async{
    return! true !=> async {return 2}
} |> Async.RunSynchronously

// unwrap async mapping 
let inline (-=>) condition value = if condition then value |> Async.RunSynchronously |> Some else None
false -=> async {return 2}
true -=> async {return 2}
val condition : bool
val value : 'a
union case Option.Some: Value: 'T -> Option<'T>
union case Option.None: Option<'T>
val value : Lazy<'T>
Multiple items
active recognizer Lazy: Lazy<'T> -> 'T

--------------------
type Lazy<'T> = System.Lazy<'T>
member System.Lazy.Force : unit -> 'T
val value : 'a option
val value : Async<'a>
val async : AsyncBuilder
val a : 'a
Multiple items
type Async =
  static member AsBeginEnd : computation:('Arg -> Async<'T>) -> ('Arg * AsyncCallback * obj -> IAsyncResult) * (IAsyncResult -> 'T) * (IAsyncResult -> unit)
  static member AwaitEvent : event:IEvent<'Del,'T> * ?cancelAction:(unit -> unit) -> Async<'T> (requires delegate and 'Del :> Delegate)
  static member AwaitIAsyncResult : iar:IAsyncResult * ?millisecondsTimeout:int -> Async<bool>
  static member AwaitTask : task:Task -> Async<unit>
  static member AwaitTask : task:Task<'T> -> Async<'T>
  static member AwaitWaitHandle : waitHandle:WaitHandle * ?millisecondsTimeout:int -> Async<bool>
  static member CancelDefaultToken : unit -> unit
  static member Catch : computation:Async<'T> -> Async<Choice<'T,exn>>
  static member Choice : computations:seq<Async<'T option>> -> Async<'T option>
  static member FromBeginEnd : beginAction:(AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
  ...

--------------------
type Async<'T> =
static member Async.RunSynchronously : computation:Async<'T> * ?timeout:int * ?cancellationToken:System.Threading.CancellationToken -> 'T
Raw view Test code New version

More information

Link:http://fssnip.net/872
Posted:1 year ago
Author:Pavel Tatarintsev
Tags: map , operators