将列表元素(相邻)打包成2元组的方法

编程入门 行业动态 更新时间:2024-10-22 13:53:35
本文介绍了将列表元素(相邻)打包成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元组的方法

本文发布于:2023-07-14 21:59:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1107273.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   方法   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!