F# 重新创建一个;“树包含元素”;用折叠式的。我不知道';我不明白为什么';他在工作
我试图用一个折叠式函数重新创建一个给定树和元素x的函数,如果元素在树中,它将输出true,而不是false。 这是我的树:F# 重新创建一个;“树包含元素”;用折叠式的。我不知道';我不明白为什么';他在工作,f#,tree,fold,F#,Tree,Fold,我试图用一个折叠式函数重新创建一个给定树和元素x的函数,如果元素在树中,它将输出true,而不是false。 这是我的树: type 'a binTree = | Null // empty tree | Node of 'a * 'a binTree * 'a binTree 这是我没有折叠的代码 let rec containsTreeBis bTree y = match bTree with |
type 'a binTree =
| Null // empty tree
| Node of 'a * 'a binTree * 'a binTree
这是我没有折叠的代码
let rec containsTreeBis bTree y =
match bTree with
| Null -> false
| Node(x,left,right) ->
match x=y with
| true -> true
| _ -> containsTreeBis left y || containsTreeBis right y
这是我的折叠树函数,它将折叠应用于树:
let rec foldTree f e tree =
match tree with
| Null -> e
| Node (x, left, right) ->
f x ( foldTree f e left ) ( foldTree f e right )
他们俩都做得很好
现在来谈谈问题
我试着用折叠树做同样的事情。
我确信这是正确的代码
let containsTreeF bTree pred =
foldTree ( fun y vl vr -> pred y || vl || vr ) true bTree
但是用FsCheck做一些检查,结果是错误的
我随机将代码更改为:
let containsTreeF bTree pred =
foldTree ( fun y vl vr -> pred y || vl || vr ) false bTree
最后用false更改了true
我做了检查。它起作用了
怎么做?我不明白。您的
fold
函数实现正确,因此问题是如何使用fold
函数检查树(或任何具有fold
操作的对象)是否包含指定元素
为此,需要使用false
作为初始值,使用逻辑或
作为操作,即:
let contains x tree =
foldTree (fun y vl vr -> x = y || vl || vr) false tree
对于空树,这将返回false
。如果任一分支包含该元素,则true | | false
将为true
,但如果没有一个分支包含该元素,则false | | false
将导致false
当您将true
作为初始值时,您的FsCheck测试为什么没有捕捉到这一点?使用该初始值,您的函数将始终返回true
,因此您可以通过一个查找未包含在树中的元素的测试来捕获该值
这方面的单元测试是:
let t = Node(1, Node(2, Null, Null), Null)
contains 7 t
使用FsCheck,您可以使用随机生成的集合中的值生成树,然后检查它是否包含不在此集合中的项。不过,我在发布代码后就理解了代码。