Functional programming SML中获取子树的问题
我被困在编码中,必须在SML中获取给定节点的子树 数据类型如下所示Functional programming SML中获取子树的问题,functional-programming,sml,smlnj,Functional Programming,Sml,Smlnj,我被困在编码中,必须在SML中获取给定节点的子树 数据类型如下所示 datatype ctree = Empty | Node of char*ctree*ctree 现在我必须编写一个函数,它将返回以给定节点为根的子树 我编写了一个助手函数“nodeExist(n,tree)”,它将检查树上是否存在节点- fun getSubtree(x,ctree) = case ctree of Empty => Empty | Node(y,left,righ
datatype ctree = Empty | Node of char*ctree*ctree
现在我必须编写一个函数,它将返回以给定节点为根的子树
我编写了一个助手函数“nodeExist(n,tree)”,它将检查树上是否存在节点-
fun getSubtree(x,ctree) =
case ctree of
Empty => Empty
| Node(y,left,right) => if(nodeExist (x,ctree)) = true then Node(x,left,right) else Empty;
它没有给出正确的输出。节点(x、左、右)是否可以给出子树,或者我应该正确地遍历树以获得它。我将从注释开始尝试,因为它非常接近:
fun subtree(x, Empty) = Empty
| subtree(x, T as Node(y, left, right)) =
if x = y
then T
else subtree(x, left) orelse subtree(x, right)
但是它有一个类型问题,因为orelse
需要两个真值,而不是两棵树。你需要做一些逻辑上相似的事情,但是用树代替事实 查看前进路径的一种方法是将
orelse
重写为等效的案例分析
fun subtree(x, Empty) = Empty
| subtree(x, T as Node(y, left, right)) =
if x = y
then T
else let val l = subtree(x, left) in
case l of
true => l
| false => subtree(x, right)
end
从这里,我们可以将布尔型案例替换为树型案例:
fun subtree(x, Empty) = Empty
| subtree(x, T as Node(y, left, right)) =
if x = y
then T
else let val l = subtree(x, left) in
case l of
Node _ => l
| Empty => subtree(x, right)
end
或者,它可以重新排列一点,使它变短
fun subtree(x, Empty) = Empty
| subtree(x, T as Node(y, left, right)) =
if x = y
then T
else case subtree(x, left) of
Empty => subtree(x, right)
| t => t
(这是找到解决方案的一种非常迂回的方法,但这是我在尝试重新编写您的函数时的思路。)
节点(x,左,右)
与ctree
是同一棵树,但其根元素被x
替换。你需要穿过这棵树。(而且你不需要nodeExist
)谢谢。我用nodeExist修复了这个问题,但不知怎么的,没有它就不行了。我想做一些类似有趣的子树(x,Empty)=Empty |子树(x,t作为节点(y,左,右))=如果(x=y)那么t其他子树(x,左)或lse子树(x,右);但是orelse给出了类型不匹配错误。感谢您的详细解释。