Skip to content

Instantly share code, notes, and snippets.

@toburger
Last active August 29, 2015 14:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toburger/e2921407e39b1cf0831f to your computer and use it in GitHub Desktop.
Save toburger/e2921407e39b1cf0831f to your computer and use it in GitHub Desktop.
Cool new F# 4.0 feature
module Reflection =
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Quotations.Patterns
open System.Reflection
let private (|Name|) (info: MemberInfo) = info.Name
let private (|PropertyName|_|) = function
| PropertyGet (_, Name name, _) -> Some name
| _ -> None
let rec private (|LambdaName|_|) = function
| Lambda (_, LambdaName name) -> Some name
| Lambda (_, Call (_, Name name, _)) -> Some name
| _ -> None
type Reflector =
static member GetWithBindingName<'a>([<ReflectedDefinition(true)>] expr : Expr<'a>) =
match expr with
| WithValue (o, _, PropertyName name)
| WithValue (o, _, LambdaName name) ->
name, o :?> 'a
| expr -> failwithf "Unexpected expression: %A" expr
open System
open Reflection
let ``today's date`` = DateTime.Today
let ``now it is`` = DateTime.Now
Reflector.GetWithBindingName ``today's date`` |> printfn "%A"
Reflector.GetWithBindingName ``now it is`` |> printfn "%A"
let thefunction s = sprintf "hello, %s!" s
let name, f = Reflector.GetWithBindingName thefunction
name, f "F#"
@toburger
Copy link
Author

Output

("today's date", 24.07.2015 00:00:00)
("now it is", 24.07.2015 10:35:26)

@vasily-kirichenko
Copy link

Do you know why it's PropertyGet specifically?

@toburger
Copy link
Author

You can pattern match against other kinds of Quotations as well...

@toburger
Copy link
Author

I've updated the code so that it also works with functions:

let sayHello s = sprintf "hello, %s!" s
let name, f = Reflector.GetWithBindingName sayHello
name, f "vasily"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment