gpt4 book ai didi

f# - 动态检查联合案例

转载 作者:行者123 更新时间:2023-12-01 14:36:16 26 4
gpt4 key购买 nike

当存在值声明时,如何在 F# 中动态匹配联合案例?

非工作代码:

let myShape = Shape.Square
expect myShape Shape.Circle

type Shape =
| Circle of int
| Square of int
| Rectangle of ( int * int )

let expect someShape someUnionCase =
if not ( someShape = someUnionCase )
then failwith ( sprintf "Expected shape %A. Found shape %A" someShape someUnionCase )

let myShape = Shape.Square
expect myShape Shape.Circle // Here I want to compare the value types, not the values

如果我的联合案例没有声明值,这可以使用实例化样本(这不是我想要的):

let myShape = Shape.Square
expect myShape Shape.Circle

type Shape =
| Circle
| Square
| Rectangle

let expect someShape someUnionCase =
if not ( someShape = someUnionCase )
then failwith ( sprintf "Expected shape %A. Found shape %A" someShape someUnionCase )

let myShape = Shape.Square
expect myShape Shape.Circle // Comparing values instead of types

最佳答案

有趣的是,这在 C# 中可以很容易地完成,但 F# 编译器不允许您调用函数 - 这看起来很奇怪。

规范说受歧视的联盟将有(第 8.5.3 节):

One CLI instance property u.Tag for each case C that fetches or computes an integer tag corresponding to the case.

所以我们可以简单地用 C# 编写您的 expect 函数

public bool expect (Shape expected, Shape actual)
{
expected.Tag == actual.Tag;
}

关于为什么这不能在 F# 代码中完成,这是一个有趣的问题,规范似乎没有给出一个很好的理由。

关于f# - 动态检查联合案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9309019/

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