如何在列表列表上获得递归功能的输出,如何获得多个列表?
我正在尝试使用一个递归功能,该功能打印所有具有最大长度列表中最大长度的列表(如果它们的长度相同,则可能是一个或多个)
给定输入,例如:
[[],[3],[2],[6],[3,6],[2,6],[4],[3,4],[2,4],[5],[3,5],[2,5],[4,5],[3,4,5],[2,4,5],[1]]
输出应包含两个最长列表
[3,4,5],[2,4,5]
:以下功能仅打印第一个列表:[3,4,5]
longest :: Ord a => [[a]] -> [a]
longest [y] = y --base case: if there's only one element left, return it.
longest (x:y:lst) --extract the first two elements x, y from the list.
| length x < length y = longest (y:lst)
| otherwise = longest (x:lst)
注意:我必须使用恢复
I am trying to use a recursive function that prints all lists that has the maximum length out of the lists ( could be one or more if they have the same length)
given an input such as :
[[],[3],[2],[6],[3,6],[2,6],[4],[3,4],[2,4],[5],[3,5],[2,5],[4,5],[3,4,5],[2,4,5],[1]]
the output should contain both the longest lists :
[3,4,5],[2,4,5]
My following function prints only the first list: [3,4,5]
longest :: Ord a => [[a]] -> [a]
longest [y] = y --base case: if there's only one element left, return it.
longest (x:y:lst) --extract the first two elements x, y from the list.
| length x < length y = longest (y:lst)
| otherwise = longest (x:lst)
Note: I must used recuersion
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用累加器跟踪迄今为止获得的最长项目以及此列表的列表,因此:
You can use accumulators to keep track of the thus far obtained longest item and the list of lists for this, so:
我发现您的方法很复杂,因为您将在参数开始时积累结果,并且有必要进一步使用。
考虑此解决方案,该解决方案将未来结果累积到第二个辅助参数中。
输出:
您可以在此设计中的SO或标准库中在Haskell中看到这种方法:
I find your approach complicated in that you will accumulate the result at the beginning of the parameter, and it is necessary to work with it further.
Consider this solution, which accumulates the future result into a second auxiliary parameter.
Output:
This approach you can see in Haskell on the SO or in the standard libraries in this design: