有什么更好的建模treeNode的方法? [英] What is a better way to model a treeNode?
问题描述
以下两种创建树节点的方法的优缺点是什么?
What are the pros and cons of each of the following two ways to create a tree node?
type TreeNode = | TreeNode of int * (TreeNode option) * (TreeNode option) * (TreeNode option)
type Node = | Node of int * Node * Node
| None
推荐答案
它们非常接近,但并不完全等效.实际上,您可以使用数学很好地推理出功能类型(例如,请参见我最近的文章),但您甚至可以非正式地看到它.
They are very close, but not entirely equivalent. You can actually reason about functional types quite nicely using mathematics (see for example my recent article), but you can see that even informally.
鉴于任何TreeNode(num, optLeft, optRight)
,您始终可以创建一个包含相同信息的Node
(选项类型的None
将映射到Node.None
).
Given any TreeNode(num, optLeft, optRight)
, you can always create a Node
containing the same information (None
of the option type will be mapped to Node.None
).
有趣的是,这反过来是行不通的.如果有人给您Node.None
,则您不能将其转换为TreeNode
,因为TreeNode
的根中至少需要一个整数.
Interestingly, this does not work the other way round. If someone gives you Node.None
, you cannot turn it into TreeNode
, because TreeNode
needs at least one integer in the root.
因此,它们等效,除了第二个允许空树.从实际的角度来看,第二种类型似乎更易于使用(因为您只需要在一个地方处理空树).
So, they are equivalent with the exception that the second one allows empty trees. From the practical perspective, the second type seems easier to use (because you only have to handle empty tree in one place).
这篇关于有什么更好的建模treeNode的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!