需要根据元素的升序将列表划分为列表(Haskell) [英] Need to partition a list into lists based on breaks in ascending order of elements (Haskell)

查看:28
本文介绍了需要根据元素的升序将列表划分为列表(Haskell)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的列表:

[4,5,6,7,1,2,3,4,5,6,1,2]

我需要一个 Haskell 函数来将这个列表转换成一个列表列表,这些列表由原始列表的片段组成,这些片段按升序形成一个系列.所以结果应该是这样的:

I need a Haskell function that will transform this list into a list of lists which are composed of the segments of the original list which form a series in ascending order. So the result should look like this:

[[4,5,6,7],[1,2,3,4,5,6],[1,2]]

有什么建议吗?

推荐答案

ascend :: Ord a => [a] -> [[a]]
ascend xs = foldr f [] xs
  where
    f a []  = [[a]]
    f a xs'@(y:ys) | a < head y = (a:y):ys
                   | otherwise = [a]:xs'

在 ghci 中

*Main> ascend [4,5,6,7,1,2,3,4,5,6,1,2]
[[4,5,6,7],[1,2,3,4,5,6],[1,2]]

这篇关于需要根据元素的升序将列表划分为列表(Haskell)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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