检查树之间相等性的函数
如何在Scheme中实现一个相等函数,它需要两棵树并检查它们是否具有相同的元素和结构?
How can I implement an equality function in Scheme that takes 2 trees and checks if they have both the same elements and structure?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从每棵树的根开始递归
如果根值相似 - 继续左子树,然后是右子树
任何差异 - 打破
recursion from the root each of the trees
if the root values are similar - continue with the left subtree, then right subtree
any difference - break
我们可以使用等于?
但是,为了一些乐趣,继 Vasserman 提到“中断”之后,这可能是利用计划连续控制能力的好机会!
如果我们发现树中存在任何差异,我们可以使用 call/cc 发出提前返回。这样我们就可以跳回调用者继续,而不必展开堆栈。
这是一个非常简单的例子。它假设树的形状良好,并且仅包含作为叶子的符号,但它应该有望演示这个概念。您将看到该过程明确接受延续作为参数。
call/cc 让我们捕获当前的延续。我是这样调用这个过程的:
We could use equal?
But, for some fun, following on from Vassermans mention of a "break", this might be a good chance to take advantage of Schemes continuation controlling power!
We can use call/cc to issue an early return if we notice any difference in the trees. This way we can just jump back to the callers continuation without having to unwind the stack.
Here is a really simple example. It assumes the trees are well-formed and only contain symbols as leaves, but it should hopefully demonstrate the concept. You'll see that the procedure explicitly accepts the continuation as a parameter.
call/cc lets us capture the current continuation. Here is how I called this procedure:
我也得到了一个连续的答案。但现在我有两个延续,一个是真的,一个是假的。如果您想根据结果进行分支,这非常有用。我还添加了“相同?”,它隐藏了所有延续,因此您不必处理它们。
I've also got a continuation-ful answer. But now I have two continuations, one if it is true, and one if it is false. This is useful if you want to branch on the result. I've also included 'same?, which hides all the continuations so you don't have to deal with them.