在 Haskell 中添加列表的惯用方法是什么?

发布于 2024-10-13 09:12:17 字数 201 浏览 2 评论 0原文

假设我想在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

天涯沦落人 2024-10-20 09:12:17

有一个 zipWith 使用提供的函数组合两个列表的库函数。它完全按照您的要求进行操作,您将得到:

addLists = 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:

addLists = zipWith (+)

This uses (+) to combine the elements of lists given as further arguments.

沐歌 2024-10-20 09:12:17

Applicative Functor 风格:

import Control.Applicative

addLists xs ys = getZipList $ (+) <
gt; ZipList xs <*> ZipList ys

请注意,这非常丑陋,因为有两种方法可以使 List 成为 Applicative Functor。第一种(恕我直言,不太有用)方法是采用所有组合,这种方法成为“标准”,所以 (+) <$> [1,2] <*> [30,40][31,41,32,42]。另一种方法是根据我们的需要压缩列表,但由于每种类型只能有一个类型类实例,因此我们必须将列表包装在 ZipLists 中,并使用 getZipList 解开结果。

Applicative Functor style:

import Control.Applicative

addLists xs ys = getZipList $ (+) <
gt; ZipList xs <*> ZipList ys

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.

愿与i 2024-10-20 09:12:17
addLists xs ys = zipWith (+) xs ys
addLists xs ys = zipWith (+) xs ys
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文