rsi*_*nha 7 haskell applicative
我很好奇在ghc中定义了getZipList的位置.Control.Applicative对ZipList有这个定义.
newtype ZipList a = ZipList { getZipList :: [a] }
Run Code Online (Sandbox Code Playgroud)
使用ZipLists的一种方法是(来自LYAH):
ghci> getZipList $ (+) <$> ZipList [1,2,3] <*> ZipList [100,100,100]
[101,102,103]
Run Code Online (Sandbox Code Playgroud)
我很好奇getZipList如何知道返回什么.也许我错过了关于newtype关键字的一些东西.谢谢!
Dan*_*her 11
它不仅仅是newtype,它的工作原理与之相同data.您似乎不知道的是命名字段语法,
newtype ZipList a = ZipList { getZipList :: [a] }
Run Code Online (Sandbox Code Playgroud)
几乎是一样的
newtype ZipList a = ZipList [a]
getZipList :: ZipList a -> [a]
getZipList (ZipList xs) = xs
Run Code Online (Sandbox Code Playgroud)
但是命名字段语法允许更方便的更新和模式匹配 - 特别是对于data具有多个字段的类型中的命名字段更方便.
命名字段(隐式)定义访问器函数,该函数从包装值中提取包含的数据.