2017-04-25 76 views
3

如何通過填寫magic來完成此測試?DU案例名稱

type DU = 
    | ACaseName 
    | BThereCake 

let magic (q: Quotation<_>): string = 
    // smallest F# code in here? 

open Expecto 
let subject = magic <@ ACaseName @> 
Expect.equal subject "ACaseName" "Should extract the NAME of the DU case" 

回答

10

在這種情況下,下面會做什麼:

open Microsoft.FSharp.Quotations 

let magic (q: Expr<_>): string = 
    match q with 
    | Patterns.NewUnionCase(case, args) -> case.Name 
    | _ -> failwith "Not a union case" 

let subject = magic <@ ACaseName @> 

的問題是,你要當工會的情況下有一定的論據做什麼。例如:

type DU = 
    | ACaseName 
    | BThereCake of int 

如果你想從<@ BThereCake @>提取名稱,而不是僅僅從<@ BThereCake(12) @>,那麼你需要添加更多的情況:

let magic (q: Expr<_>): string = 
    match q with 
    | DerivedPatterns.Lambdas(_, Patterns.NewUnionCase(case, args)) 
    | Patterns.NewUnionCase(case, args) -> case.Name 
    | _ -> failwith "Not a union case" 

let subject = magic <@ BThereCake @> 
+1

我只是想而不案件的名稱。 :) – Henrik