列表中的元素对 [英] Pairs of elements from list

查看:31
本文介绍了列表中的元素对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 [1,2,3,4] 转换为 [[1 2] [2 3] [3 4]][(1 2) (2 3) (3 4)].在 clojure 我有 (partition 2 1 [1,2,3,4]).我怎样才能在haskell中做到这一点?我怀疑标准api中有这样的功能,但我找不到.

I want to convert [1,2,3,4] to [[1 2] [2 3] [3 4]] or [(1 2) (2 3) (3 4)]. In clojure I have (partition 2 1 [1,2,3,4]). How can I do it in haskell? I suspect there is such function in standard api but I can't find it.

推荐答案

为此的标准技巧是使用它自己的 tail zip 列表:

The standard trick for this is to zip the list with it's own tail:

> let xs = [1,2,3,4] in zip xs (tail xs)
[(1,2),(2,3),(3,4)]

要了解为什么会这样,请在视觉上排列列表及其尾部.

To see why this works, line up the list and its tail visually.

      xs = 1 : 2 : 3 : 4 : []
 tail xs = 2 : 3 : 4 : []

并注意 zip 正在从每一列中生成一个元组.

and note that zip is making a tuple out of each column.

为什么这样做总是正确的,还有两个更微妙的原因:

There are two more subtle reasons why this always does the right thing:

  • zip 在任一列表用完元素时停止.这在这里很有意义,因为我们不能在最后有一个不完整的对",而且它还确保我们不会从单个元素列表中得到对.
  • xs 为空时,人们可能期望 tail xs 抛出异常.但是,因为 zip首先检查它的第一个参数,当它看到它是空列表时,第二个参数永远不会被评估.
  • zip stops when either list runs out of elements. That makes sense here since we can't have an "incomplete pair" at the end and it also ensures that we get no pairs from a single element list.
  • When xs is empty, one might expect tail xs to throw an exception. However, because zip checks its first argument first, when it sees that it's the empty list, the second argument is never evaluated.

上述所有内容也适用于 zipWith,因此您可以在需要将函数成对应用于相邻元素时使用相同的方法.

Everything above also holds true for zipWith, so you can use the same method whenever you need to apply a function pairwise to adjacent elements.

对于像 Clojure 的 partition 这样的通用解决方案,标准库中没有任何内容.但是,您可以尝试以下操作:

For a generic solution like Clojure's partition, there is nothing in the standard libraries. However, you can try something like this:

partition' :: Int -> Int -> [a] -> [[a]]
partition' size offset
  | size <= 0   = error "partition': size must be positive"
  | offset <= 0 = error "partition': offset must be positive"
  | otherwise   = loop
  where
    loop :: [a] -> [[a]]
    loop xs = case splitAt size xs of
                -- If the second part is empty, we're at the end. But we might
                -- have gotten less than we asked for, hence the check.
                (ys, []) -> if length ys == size then [ys] else []
                (ys, _ ) -> ys : loop (drop offset xs)

这篇关于列表中的元素对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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