将列表元素(相邻)打包成2元组的方法 [英] Ways to pack (adjacent) elements of a list into 2-tuples

查看:67
本文介绍了将列表元素(相邻)打包成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.

谢谢!

推荐答案

通过此提示,我们可以轻松地将列表分为两个列表,其中包含交替元素(

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元组的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆