Ways to pack (adjacent) elements of a list into 2-tuples

前端 未结 4 1510
被撕碎了的回忆
被撕碎了的回忆 2021-01-23 02:57

I was wondering if there would be a concise/one-liner way to do the following:

pack :: [a] -> [(a, a)]
pack []       = []
pack [_]      = []
pack (x:y:xs) = (         


        
4条回答
  •  遥遥无期
    2021-01-23 03:22

    Another one-liner using LambdaCase and Data.List.unfoldr:

    pack = unfoldr $ \case (x:y:zs) -> Just ((x,y),zs); _ -> Nothing
    

    Something I want occasionally is splits -

    splits :: Int -> [a] -> [[a]]
    splits n = unfoldr $ \case [] -> Nothing ; xs -> Just $ splitAt n xs
    

    And given that, pack becomes:

    pack xs = [ (a,b) | [a,b] <- splits 2 xs ]
    

提交回复
热议问题