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

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

    We can easily split the list into two lists with alternating elements with this tidbit (due to HaskellWiki)

     foldr (\a ~(x,y) -> (a:y,x)) ([],[])
    

    All that remains is to combine the lists with zip

    pack :: [a] -> [(a, a)]
    pack = uncurry zip . foldr (\a ~(x,y) -> (a:y,x)) ([],[])
    

提交回复
热议问题