Skip to content

Instantly share code, notes, and snippets.

@habib-sadullaev
Last active November 6, 2020 06:31
Show Gist options
  • Save habib-sadullaev/a5a9975d1261db4e2f04829fa8cab7b0 to your computer and use it in GitHub Desktop.
Save habib-sadullaev/a5a9975d1261db4e2f04829fa8cab7b0 to your computer and use it in GitHub Desktop.
option builder
open System
open System.Runtime.CompilerServices
[<Extension>]
type X =
[<Extension>]
static member Bind(_: OptionBuilder, v: 'a, f: 'a -> 'b option) =
match box v with
| null -> None
| :? string as v when String.IsNullOrEmpty v -> None
| _ -> f v
[<Extension>]
static member Return(this: OptionBuilder, x: 'a) = this.Bind(x, Some)
[<Extension>]
static member Bind(this: OptionBuilder, v: 'a option, f: 'a -> 'b option) = v |> Option.bind (fun x -> this.Bind(x, f))
[<Extension>]
static member ReturnFrom(this: OptionBuilder, x: 'a option) = x |> Option.bind (fun x -> this.Bind(x, Some))
and OptionBuilder() =
member this.Bind(x: Nullable<'a> option, f: 'a -> 'b option) = x |> Option.bind (fun x -> this.Bind(x, f))
member _.Bind(x: Nullable<'a>, f: 'a -> 'b option) = Option.bind f (Option.ofNullable x)
member this.ReturnFrom(x: Nullable<'a>) = this.Bind(x, Some)
member this.ReturnFrom(x: Nullable<'a> option) = this.Bind(x, Some)
option { return Nullable<int>() }
option { return! Nullable<int>() }
option { return! Some (Nullable<int>()) }
option { return Unchecked.defaultof<string> }
option { return "" }
option { return! Some Unchecked.defaultof<string> }
option { return! Some "" }
option { let! (str: string) = null in return int str }
option { let! x = Some 3
let! y = None
return float x + y }
option { let! x = Some 3.0
let! y = Some 5
let! z = None
return x + float y + z }
option { let! x = Nullable 5M
let! y = Some (Nullable())
let! z = None
return x + y + z }
option { let! x = Unchecked.defaultof<string>
let! y = ""
return x.StartsWith y }
option { let! x = "aaa"
let! y = Some null
return x = y }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment