问题描述
在python zip 函数中可以接受任意数量的列表并将它们拉到一起。
In python zip function accepts arbitrary number of lists and zips them together.
>>> l1 = [1,2,3] >>> l2 = [5,6,7] >>> l3 = [7,4,8] >>> zip(l1,l2,l3) [(1, 5, 7), (2, 6, 4), (3, 7, 8)] >>>
如何将 zip haskell?
How can I zip together multiple lists in haskell?
推荐答案
可以使用。由于新类型的打包/解包使用起来有点不愉快,但如果你正在做一些无法用 zipWithn 完成的小n,你很可能已经处于一个足够高的抽象层次中,无论如何,这些标记性的痛苦都不存在。
A generalization of zip can be achieved using Applicative Notation. It's a bit unpleasant to use because of the newtype wrapping/unwrapping, but if you are doing something that can't be done with a zipWithn for reasonably small n, you are probably already at a high enough level of abstraction where the notational pains are absent anyway.
类型是 ZipList a ,并将其应用实例拉到一起列表。例如:
The type is ZipList a, and its applicative instance zips together lists. For example:
(+) <$> ZipList [1,2] <*> ZipList [3,4] == ZipList [4,6]
这概括为任意数组的函数并使用部分申请类型:
This generalizes to functions of arbitrary arity and type using partial application:
(+) <$> ZipList [1,2] :: ZipList (Int -> Int)
部分适用于此?
如果您不喜欢到处添加ZipList和getZipList,您可以轻松地重新创建符号:
If you don't like adding ZipList and getZipList everywhere, you could recreate the notation easily enough:
(<$>) :: (a -> b) -> [a] -> [b] (<$>) = map (<*>) :: [a -> b] -> [a] -> [b] (<*>) = zipWith ($)
符号 zipWith fabcd ... 为:
Then the notation for zipWith f a b c d ... is:
f <$> a <*> b <*> c <*> d <*> ...
应用符号是一种功能非常强大且通用的技术,其范围比广义拉链。有关应用符号的更多信息,请参阅。
Applicative notation is a very powerful and general technique that has much wider scope than just generalized zipping. See the Typeclassopedia for more on Applicative notation.
这篇关于如何在Haskell中压缩多个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!