Skip to content

Instantly share code, notes, and snippets.

@caindy
Last active August 29, 2015 14:11
Show Gist options
  • Save caindy/3b657d112450090c215c to your computer and use it in GitHub Desktop.
Save caindy/3b657d112450090c215c to your computer and use it in GitHub Desktop.
The lines that use the (?) operator are compiler errors. I suspect this fails for the same reason that you cannot add operators in type extensions. I just don't know what that reason is...
[<AutoOpen>]
module Auto =
type Result<'s, 'f> =
| Success of 's
| Failure of 'f
open System
open System.Runtime.CompilerServices
open System.Collections.Generic
open Newtonsoft.Json.Linq
type JObject with
member inline this.Get (n: string) =
let l = n.ToLowerInvariant()
let matchKey (p: JProperty) = p.Name.ToLowerInvariant() = l
match this.Properties() |> Seq.tryFind matchKey with
| Some o -> Some <| o.Value.Value<'t>()
| None -> None
[<Extension>]
type Extensions () =
[<Extension>]
static member inline Get (i: IDictionary<string,Object>, n: string) =
let l = n.ToLowerInvariant()
let matchKey (KeyValue(n': string, o)) = n'.ToLowerInvariant() = n
match i |> Seq.tryFind matchKey with
| Some (KeyValue(k,v)) -> Some (v :?> 't)
| None -> None
let inline (?) (x: ^a) (n: string) : Result<'t,string> =
try
match (^a : (member Get : string -> 't option) (x, n)) with
| Some v -> Success v
| None -> Failure n
with _ -> Failure n
let foo () =
let d = dict [||]
d?foo |> ignore
let j = JObject()
j.Get("foo") |> ignore
j?foo |> ignore
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment