gpt4 book ai didi

f# - 在有区别的联合类型声明中使用事件模式

转载 作者:行者123 更新时间:2023-12-04 17:37:31 25 4
gpt4 key购买 nike

是否可以在有区别的联合类型声明中使用事件模式?

更准确地说,请考虑以下玩具示例:

type T = 
| A of int
| B

let (|Negative|_|) t =
match t with
| A n when n < 0 -> Some ()
| _ -> None

let T_ToString = function
| Negative () -> "negative!"
| _ -> "foo!"

现在假设我想覆盖 T 中的 ToString()。在 T 的类型声明中,我不能引用 T_ToString,因为此时尚未声明 T_ToString。我无法在 ToString() 之前移动事件模式和 T_ToString,因为此时 T 尚未声明。但这也不起作用:
type T = 
| A of int
| B

static member (|Negative|_|) t =
match t with
| A n when n < 0 -> Some ()
| _ -> None

override this.ToString () =
match this with
| Negative () -> "negative!"
| _ -> "foo!"

最佳答案

您的问题表明测试是否为负值是 T 的内在操作,所以它应该是其定义的一部分。定义属性是一种方法:

type T = 
| A of int
| B

member this.IsNegative =
match this with
| A n -> n < 0
| _ -> false

override this.ToString() =
if this.IsNegative then "negative!"
else "foo!"

我不确定是否仍然需要事件模式,但如果它是微不足道的:
let (|Negative|_|) (x: T) = if x.IsNegative then Some() else None

关于f# - 在有区别的联合类型声明中使用事件模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13841897/

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