Last active
August 29, 2015 14:25
-
-
Save toburger/e2921407e39b1cf0831f to your computer and use it in GitHub Desktop.
Cool new F# 4.0 feature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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#" |
Do you know why it's PropertyGet
specifically?
You can pattern match against other kinds of Quotations as well...
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
Output