What is an idiomatic way to add lists in Haskell?

我与影子孤独终老i 提交于 2019-11-30 03:20:11

问题


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

回答1:


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.




回答2:


Applicative Functor style:

import Control.Applicative

addLists xs ys = getZipList $ (+) <$> 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.




回答3:


addLists xs ys = zipWith (+) xs ys


来源:https://stackoverflow.com/questions/4776750/what-is-an-idiomatic-way-to-add-lists-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!