8

我很好奇 getZipList 在 ghc 中的定义位置。Control.Applicative 对 ZipList 有这个定义。

newtype ZipList a = ZipList { getZipList :: [a] }

使用 ZipLists 的一种方法是(来自 LYAH):

ghci> getZipList $ (+) <$> ZipList [1,2,3] <*> ZipList [100,100,100]

[101,102,103]

我很好奇 getZipList 如何知道要返回什么。也许我错过了关于 newtype 关键字的一些东西。谢谢!

4

2 回答 2

12

不只是newtype,它与data. 您似乎不知道的是命名字段语法,

newtype ZipList a = ZipList { getZipList :: [a] }

几乎一样

newtype ZipList a = ZipList [a]

getZipList :: ZipList a -> [a]
getZipList (ZipList xs) = xs

data但是命名字段语法允许更方便的更新和模式匹配 - 特别是对于具有多个字段的类型中的命名字段更加方便。

命名字段(隐式)定义了从包装值中提取包含数据的访问器函数。

于 2013-01-18T20:59:19.183 回答
3

秘密不在新类型定义中,而是在 <*> 的应用实例中

instance Applicative ZipList where  
pure x = ZipList (repeat x)  
ZipList fs <*> ZipList xs = ZipList [f x | (f,x) <- zip fs xs]

默认列表是这样的,这就是差异的来源

instance Applicative [] where  
pure x = [x]  
fs <*> xs = [f x | f <- fs, x <- xs]  
于 2013-01-18T21:02:32.977 回答