gpt4 book ai didi

f# - DU 案件名称

转载 作者:行者123 更新时间:2023-12-01 07:52:15 27 4
gpt4 key购买 nike

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

最佳答案

在这种情况下,将执行以下操作:

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

关于f# - DU 案件名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43616531/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com