문제

I am curious about where getZipList is defined in ghc. Control.Applicative has this definition for ZipList.

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

One way to use ZipLists is (from LYAH):

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

[101,102,103]

I am curious how getZipList knows what to return. Perhaps I am missing something about the newtype keyword. Thanks!

도움이 되었습니까?

해결책

It's not just newtype, it works the same with data. What you seem to be unaware of is named field syntax,

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

is almost the same as

newtype ZipList a = ZipList [a]

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

but the named field syntax allows more convenient updating and pattern matching - in particular it's much more convenient for named fields in data types with multiple fields.

The named field (implicitly) defines the accessor function that extracts the contained data from the wrapped value.

다른 팁

The secret is not in the newtype definition but in the applicative instance it has for <*>

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

The default list is like this instead, and that is where the difference comes from

instance Applicative [] where  
pure x = [x]  
fs <*> xs = [f x | f <- fs, x <- xs]  
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top