[英]What is the idiomatic way to refer to a singleton list constructor in Haskell?
[英]What is an idiomatic way to add lists in Haskell?
假設我想在Haskell中添加兩個列表。 最常用的方法是什么?
這是我做的:
addLists :: (Integral a) => [a] -> [a] -> [a]
addLists xs ys = map add $ zip xs ys
where add (x, y) = x+y
適用的Functor風格:
import Control.Applicative
addLists xs ys = getZipList $ (+) <$> ZipList xs <*> ZipList ys
請注意,這是如此丑陋,因為有兩種方法可以使List成為Applicative Functor。 第一種(和恕我直言不太有用)的方式是采取所有組合,這種方式成為“標准”,所以(+) <$> [1,2] <*> [30,40]
是[31,41,32,42]
。 另一種方法是在這里按需要壓縮列表,但由於每種類型只能有一個類型類實例,我們必須將列表包裝在ZipLists中,並使用getZipList解包結果。
addLists xs ys = zipWith (+) xs ys
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.