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

前端 未结 4 1543
被撕碎了的回忆
被撕碎了的回忆 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:19

    I don't know if this is one line, but:

    snd $ foldr (\ x (z, ps) -> maybe (Just x, ps) (\y -> (Nothing, (x, y) : ps) z) (Nothing, []) $ xs
    

    should be the same as your function.

提交回复
热议问题