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

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

    Note that for xs = [x1, x2, ..., xn-1, xn], we have

    init xs = [x1, x2, ... , xn-1]
    tail xs = [x2, x3, ... , xn  ]
    

    leading to

    zip (init xs) (tail xs) = [(x1, x2), (x2, x3), (x3, x4), ...]
    

    and what we want is

    pack xs                 = [(x1, x2),           (x3, x4), ...]
    

    which is easy to get once we have a list of masks

    cycle [True, False]     = [ True,    False,    True, ...    ]
    

    leading to the one-liner

    pack :: [a] -> [(a, a)]
    pack xs = map snd . filter fst . zip (cycle [True, False]) $ zip (init xs) (tail xs)
    

提交回复
热议问题