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

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

问题描述

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

我需要一个Haskell函数将这个列表转换成由原始列表的段组成的列表,它们按升序形成一系列列表。所以结果应该如下所示:

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

有何建议?

解决方案

  ascend :: Ord a => [a]  - > [[a]] 
ascend xs = foldr f [] xs
其中
f a [] = [[a]]
f a xs'@(y:ys)| a<头y =(a:y):ys
|否则= [a]:xs'

在ghci

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


Say I have any list like this:

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

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]]

Any suggestions?

解决方案

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'

In 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天全站免登陆