其他人建议的解决方法,但我建议你不要你想你的方式A(A(A(A(A(0)))))
,并A(A(A(A(B(0)))))
(语言试图强迫你)是一个更好的选择。
让我们来看看你的树型。您有两种不同的东西:包含其他树节点的树节点或包含数据的树节点。你要做的是用相同的名称呼叫这两样东西:
type test =
| A of int
| A of test
这些名称不是特别具有描述性。让它们重命名为
type Tree =
| Node of int
| Node of Tree
现在,当你通过你的树结构的工作,你需要从案“树节点”除了告诉“INT的节点”的情况:如果这是一个“节点的int“,你会想要(比如说)提取int并在计算中使用它。但是如果它是一个“树的节点”,你会想要(比如说)进一步深入树形结构,最终到达彩虹末端的金罐......我的意思是,在结束时的int树。
所以,你需要写一个match
结构类似如下:
let rec diveTree calculation node =
match node with
| Node a -> match a with
| :? int -> calculation a
| :? Tree -> diveTree calculation a
但是,如果我们做了什么F#是试图迫使你做,并用不同名称为“包含一个int”和“包含另一个树”的情况?然后你的类型将是这样的:
type Tree =
| LeafNode of int
| TreeNode of Tree
而且match
结构会是什么样子:
let rec diveTree calculation node =
match node with
| LeafNode a -> calculation a
| TreeNode a -> diveTree calculation a
我想你会发现后者更容易阅读和理解前者。而即是为什么F#要求您为歧视联盟的不同情况使用不同的标签。
另一种方法是'type test = A test option' –