gpt4 book ai didi

f# - 可区分联合中的类型约束

转载 作者:行者123 更新时间:2023-12-05 01:07:34 26 4
gpt4 key购买 nike

考虑一下

type Foo =
| I of int
| S of string



let test = [ I(5); I(9); I(7)]

它有效,但现在我希望“测试”也是 Foo 类型,并且仍然是 I 或 S 的列表。
let test = L( [ I(5); I(9); I(42) ] ) //works!
let test2 = L( [ I(5); I(9); S("stuff") ] ) //type error
let test3 = L( [ I(5); I(9); L([]) ] ) //type error

我试试那个..
type Foo =
| I of int
| S of string
| L of 'T list when 'T :> Foo

我知道这显然不起作用。写作对我来说是很自然的事情。

非常感谢帮助!!

最佳答案

您不能对“有区别的联合”使用泛型类型约束。但是您可以将特定类型固定到该 Discriminated 联合,如下所示。

type Foo = 
| I of int
| S of string
| L of Foo list


// Usage
let test = L( [ I(5); I(9); S("stuff"); L([]); I(42) ] )

这是否回答你的问题?

关于f# - 可区分联合中的类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1360048/

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