考虑一下
type Foo =
| I of int
| S of string
let test = [ I(5); I(9); I(7)]
Run Code Online (Sandbox Code Playgroud)
它有效,但现在我希望'test'也是Foo类型,并且仍然是我或SEg的列表
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
Run Code Online (Sandbox Code Playgroud)
我试试..
type Foo =
| I of int
| S of string
| L of 'T list when 'T :> Foo
Run Code Online (Sandbox Code Playgroud)
我知道它显然不起作用.这对我来说是一件很自然的事情.
非常感谢帮助!!
您不能对"区别联合"使用泛型类型约束.但是您可以将特定类型固定到Discriminated union,如下所示.
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) ] )
Run Code Online (Sandbox Code Playgroud)
这是否回答你的问题?
克里斯有一个很好的答案.如果您不希望列表嵌套,您也可以这样做
type FooAtom =
| I of int
| S of string
type Foo =
| A of FooAtom
| L of FooAtom list
let test = L( [ I(5); I(9); S("stuff"); I(42) ] )
let test2 = A( I(5) )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1366 次 |
| 最近记录: |