[Haskell-cafe] Why is there no Zippable class? Would this work?

Ryan Ingram ryani.spam at gmail.com
Thu Jul 16 20:40:05 EDT 2009


(I'm going to play fast and loose with constructors for this post,
treating MyList and ZipList as if they were [])

On Thu, Jul 16, 2009 at 4:10 PM, Dan Weston<westondan at imageworks.com> wrote:
> -- different from [], sum rather than product
> instance Applicative MyList where
>  pure x = x ::: Nil
>  (<*>) (f ::: fs) (x ::: xs) = f x ::: (fs <*> xs)
>  (<*>) _ _ = Nil

Unfortunately, this instance doesn't fulfill this Applicative law:
     pure id <*> f = f

pure id <*> [1,2,3]
= [id] <*> [1,2,3]
= [id 1]
= [1]

Fortunately, the solution already exists in Control.Applicative:

> -- | Lists, but with an 'Applicative' functor based on zipping, so that
> --
> -- @f '<$>' 'ZipList' xs1 '<*>' ... '<*>' 'ZipList' xsn = 'ZipList' (zipWithn f xs1 ... xsn)@
> --
> newtype ZipList a = ZipList { getZipList :: [a] }
>
> instance Functor ZipList where
>         fmap f (ZipList xs) = ZipList (map f xs)
>
> instance Applicative ZipList where
>         pure x = ZipList (repeat x)
>         ZipList fs <*> ZipList xs = ZipList (zipWith id fs xs)

In this case:

pure id <*> [1,2,3]
= [id, id, ...] <*> [1,2,3]
= [id 1, id 2, id 3]
= [1,2,3]

  -- ryan


More information about the Haskell-Cafe mailing list