Skip to content

Instantly share code, notes, and snippets.

@cloudRoutine
Forked from kevmal/TryGetExt.fsx
Created October 1, 2015 21:33
Show Gist options
  • Save cloudRoutine/4cba476a78518ecc952c to your computer and use it in GitHub Desktop.
Save cloudRoutine/4cba476a78518ecc952c to your computer and use it in GitHub Desktop.
[<System.Runtime.CompilerServices.Extension>]
type ExtensionMethods() =
[<System.Runtime.CompilerServices.Extension>]
static member inline GetOption< ^a,'k,'v when 'a : (member TryGetValue : 'k * ('v byref) -> bool)>(this : ^a, key : 'k) =
let mutable v = Unchecked.defaultof<'v>
let scc = ( ^a : (member TryGetValue : 'k * ('v byref) -> bool) this, key, &v)
if scc then
Some v
else
None
[<System.Runtime.CompilerServices.Extension>]
static member inline GetOrDefault< ^a,'k,'v when 'a : (member TryGetValue : 'k * ('v byref) -> bool)>(this : ^a, key : 'k, defaultValue : 'v) =
let mutable v = Unchecked.defaultof<'v>
let scc = ( ^a : (member TryGetValue : 'k * ('v byref) -> bool) this, key, &v)
if scc then
v
else
defaultValue
[<System.Runtime.CompilerServices.Extension>]
static member inline Bind< ^a,'k,'v when 'a : (member TryGetValue : 'k * ('v byref) -> bool)>(this : ^a, key : 'k, f : 'v -> 'v option) =
let mutable v = Unchecked.defaultof<'v>
let scc = ( ^a : (member TryGetValue : 'k * ('v byref) -> bool) this, key, &v)
if scc then
f v
else
None
[<System.Runtime.CompilerServices.Extension>]
static member inline Return< ^a,'k,'v when 'a : (member TryGetValue : 'k * ('v byref) -> bool)>(this : ^a, v : 'v) = Some v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment