【问题标题】:Name of the DU caseDU案例名称
【发布时间】:2017-04-26 00:49:23
【问题描述】:

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

【问题讨论】:

    标签: f#


    【解决方案1】:

    在这种情况下,以下操作会:

    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
    

    如果您想从&lt;@ BThereCake @&gt; 而不仅仅是从&lt;@ BThereCake(12) @&gt; 中提取名称,那么您需要再添加一个案例:

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

    【讨论】:

    • 我只想要没有大小写的名字。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多