方案 - 找到最深的值嵌套列表 [英] Scheme - find most deeply values nested lists

查看:32
本文介绍了方案 - 找到最深的值嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天前我询问了如何找到最深嵌套的列表.我实现了给出的想法,并且奏效了.

I asked several days ago about finding the most deeply nested lists. I implemented the idea that was given, and it works.

但是还有一个问题:我还需要从嵌套列表中构建一个列表.意思是:如果我把(8)(10 11 12),改成leaf1 和leaf2,我需要返回:'(ans (leaf1 (8)) (leaf2 (10 11 12))./ans 是引用

But there is another problem: I also need to build a list from the nested list. meaning: If I change (8) and (10 11 12), to leaf1 and leaf2, I need to return: '(ans (leaf1 (8)) (leaf2 (10 11 12)). /ans is a quote

换句话说:我的功能会得到(1 (2 3) (4 (5) (7 (8) (10 11 12)))))) => 嵌套最多的列表是 (8)(10 11 12) => 我的函数将返回 '(ans (leaf1 (8)) (leaf2 (10 11 12)).

In other words: my function will get (1 (2 3) (4 (5) (7 (8) (10 11 12)))))) => the most nested lists are (8) and (10 11 12) => my function will return '(ans (leaf1 (8)) (leaf2 (10 11 12)).

我试图找到一个想法,而不是实现.谢谢.

I am trying to find an idea, not an implementation. Thanks.

推荐答案

是的,这很容易做到.目前(如果我理解正确的话)你有一个递归函数,它下降树并使用 cons 来构建一个修改后的副本(其中最深嵌套的列表被替换为某些东西).这是树递归函数的常见模式,但它们没有理由必须返回一个与它们重复出现的输入具有相似结构的值.例如,您可以编写一个函数来遍历一棵数字树并返回它们的总和.

Yes, this is easy to do. Currently (if I understand correctly) you have a recursive function that descends a tree and uses cons to build a modified copy (in which the most deeply-nested lists are replaced with something). This is a common pattern for tree-recursive functions, but there's no reason they have to return a value with a similar structure to the input they recur on. For example, you could write a function to walk a tree of numbers and return their sum.

在这种情况下,听起来您可能希望保留树递归函数的基本结构,但使用 cons 或可能的 append 来构建一个 您找到的最深层嵌套列表的平面列表.

In this case it sounds like you probably want to keep the basic structure of your tree-recursive function, but use cons or possibly append to build a flat list of the most-deeply-nested-lists you've found.

我不能从你的问题中完全分辨出来,但你可能也在寻找一种方法来编写一个返回两个单独值的函数:一个是替换了深度嵌套列表的树通过其他东西,另一个是替换位本身的平面列表.在这种情况下,您可能需要查看 Scheme 过程 valuescall-with-values,以及库形式 let-values 如果你的计划有它.请参阅 Schemewiki 常见问题解答此处了解更多信息(向下滚动).

I can't quite tell from your question, but you might also be looking for a way to write a function that returns two separate values: one being the tree with deeply-nested-lists replaced by something else, and the other being the flat list of the replaced bits themselves. In this case you might want to look into the Scheme procedures values and call-with-values, and maybe the library form let-values if your Scheme has it. See the Schemewiki FAQ here for more info (scroll down).

这篇关于方案 - 找到最深的值嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆