Implementing `pure` in ZipList

Typeclassopedia presents this problem:

Define the correct pure definition for a ZipList Applicative instance - there is only one that satisfies the law regarding pure and (<*).

I didn't know how to solve it, so I checked it in ghci

:

ghci> pure 5 :: ZipList Int
ZipList {getZipList = [5,5,5,5,5,5,5,5,5,5,5,5,5, ...

      

where ...

means infinite 5

.

Why is it implemented this way - create an endless list?

+3


source to share


1 answer


Take the identity law for the applicative functors

pure id <*> v = v                            -- Identity

      

In the context of a ZipList, we generate output by applying each function to the left of <*>

its corresponding value on the right ...

ZipList [f1, f2, f3, ....] <*> ZipList [v1, v2, v3, ....] = 
       ZipList [f1 v1, f2 v2, f3 v3, ....]

      



so to get v

back we need every function on the left to be id

.

pure id = [id, id, id, ....]

      

If the left side was the only function [id]

, the right side would only be one long.

+14


source







All Articles