如何填写magic
?
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"
答案 0 :(得分:11)
在这种情况下,将执行以下操作:
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 @>