Need to partition a list into lists based on breaks in ascending order of elements (Haskell)

后端 未结 5 1885
南方客
南方客 2020-11-30 15:31

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

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 16:16

    You can use a right fold to break up the list at down-steps:

    foldr foo [] xs
      where
        foo x yss = (x:zs) : ws
          where
            (zs, ws) = case yss of
                         (ys@(y:_)) : rest
                                | x < y     -> (ys,rest)
                                | otherwise -> ([],yss)
                         _ -> ([],[])
    

    (It's a bit complicated in order to have the combining function lazy in the second argument, so that it works well for infinite lists too.)

提交回复
热议问题