如何使用递归找到最大长度的列表?
我正在尝试使用一个递归函数,该函数打印出由我以下代码产生的最大长度的列表:
allincreasing :: Ord a => [a] -> [[a]]
allincreasing = map nub . filter isSorted . subsequences
main = do
print $ allincreasing[3,2,6,4,5,1]
我需要将下面的输出传递给找到最大长度的递归函数:
[[],[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]]
我试图做它基于我对这个问题,但我无法很好地实现递归部分。这是我的尝试:
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 = x : (longest (y:lst))
lis :: Ord a => [a] -> a
lis = length . longest . allincreasing
注意:我需要使用递归来解决最长增加序列的问题。
I am trying to use a recursive function that prints the list that has the maximum length out of the lists resulting from my following code:
allincreasing :: Ord a => [a] -> [[a]]
allincreasing = map nub . filter isSorted . subsequences
main = do
print $ allincreasing[3,2,6,4,5,1]
I need to pass the output below to a recursive function that find the one with max length :
[[],[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]]
I tried to do it using the following code based on my understanding of an answer to this question but I couldn't implement the recursion part well. Here is my attempt:
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 = x : (longest (y:lst))
lis :: Ord a => [a] -> a
lis = length . longest . allincreasing
Note: I am required to use recursion to solve the problem of longest increasing sequence.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您想跟踪Stuf anclsiede递归(例如到目前为止的最大列表...)一个使用累加器(您可以阅读有关它们在这里... ):
由于注释请求而编辑:
When you want to track stuf alongsiede recursion (like the max list so far...) one use accumulators (you could read about them here...):
Edited due to comment request: