DU案例的名称

时间:2017-04-25 16:44:32

标签: f#

如何填写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"

1 个答案:

答案 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 @>