在 Haskell 中添加列表的惯用方法是什么?
假设我想在 Haskell 中添加两个列表。最常用的方法是什么?
这就是我所做的:
addLists :: (Integral a) => [a] -> [a] -> [a]
addLists xs ys = map add $ zip xs ys
where add (x, y) = x+y
Suppose I want to add two lists in Haskell. What is the most usual way to do this?
Here's what I did:
addLists :: (Integral a) => [a] -> [a] -> [a]
addLists xs ys = map add $ zip xs ys
where add (x, y) = x+y
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有一个
zipWith
使用提供的函数组合两个列表的库函数。它完全按照您的要求进行操作,您将得到:这使用
(+)
来组合作为进一步参数给出的列表元素。There is a
zipWith
library function that combines two lists by using a supplied function. It does exactly what you want here and you get:This uses
(+)
to combine the elements of lists given as further arguments.Applicative Functor 风格:
请注意,这非常丑陋,因为有两种方法可以使 List 成为 Applicative Functor。第一种(恕我直言,不太有用)方法是采用所有组合,这种方法成为“标准”,所以
(+) <$> [1,2] <*> [30,40]
是[31,41,32,42]
。另一种方法是根据我们的需要压缩列表,但由于每种类型只能有一个类型类实例,因此我们必须将列表包装在 ZipLists 中,并使用 getZipList 解开结果。Applicative Functor style:
Note that this is so ugly because there are two ways to make List an Applicative Functor. The first (and IMHO less useful) way is to take all combination, and that way became the "standard", so
(+) <$> [1,2] <*> [30,40]
is[31,41,32,42]
. The other way is to zip the lists as we need here, but as you can have only one type class instance per type, we have to wrap the lists in ZipLists, and to unwrap the result using getZipList.