本文介绍了将列表元素(相邻)打包成2元组的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有一种简洁/单线的方法来执行以下操作:
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) = (x, y) : pack xs与以下相同:
pack' xs = [(x, y) | (x, y, i) <- zip3 xs (tail xs) [0..], even i]我对这两个选项都不抱有太大希望,但我想知道:将(,)与其他功能结合起来是否有更简洁的方法?
I don’t have much against either of these two options, but I was wondering: is there more concise way by combining (,) with some other function?
我本来以为会有这样的方法,但这使我难以理解.因此,这只是出于好奇.
I had assumed there’d be such a way, but it eludes me. So this is just out of curiosity.
谢谢!
推荐答案通过此提示,我们可以轻松地将列表分为两个列表,其中包含交替元素(由于HaskellWiki )
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)) ([],[])剩下的就是将列表与zip
pack :: [a] -> [(a, a)] pack = uncurry zip . foldr (\a ~(x,y) -> (a:y,x)) ([],[])更多推荐
将列表元素(相邻)打包成2元组的方法
发布评论