How is getZipList defined?

I am wondering 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'm curious how getZipList knows what to return. Maybe I missed something about the newtype keyword. Thanks!

+6
source share
2 answers

This is not just newtype , it works the same with data . What you don't seem to know about is called field syntax,

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

almost coincides with

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

but the syntax of the named field allows for more convenient updating and pattern matching - in particular, it is much more convenient for named fields in data types with several fields.

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

+10
source

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

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

Instead, the default list is used, and this is where the difference comes from

 instance Applicative [] where pure x = [x] fs <*> xs = [fx | f <- fs, x <- xs] 
+3
source

All Articles