1

I'm trying to write an instance of Applicative for my ZipList and I'm getting some confusing results.

data List a =
    Nil
  | Cons a (List a)
  deriving (Eq, Show)

newtype ZipList' a =
  ZipList' (List a)
  deriving (Eq, Show)

instance Applicative ZipList' where
  pure = ZipList' . flip Cons Nil
  (<*>) (ZipList' Nil) _ = ZipList' Nil
  (<*>) _ (ZipList' Nil) = ZipList' Nil
  (<*>) (ZipList' (Cons f fs)) (ZipList' (Cons x xs)) =
    ZipList' $ Cons (f x) (fs <*> xs)

It works as expected for ZipLists of length 1 or 2:

> ZipList' (Cons (*2) (Cons (+9) Nil)) <*> ZipList' (Cons 5 (Cons 9 Nil))
ZipList' (Cons 10 (Cons 18 Nil))

But when I go to 3+, I get some odd results:

> ZipList' (Cons (*2) (Cons (+99) (Cons (+4) Nil))) <*> ZipList' (Cons 5 (Cons 9 (Cons 1 Nil)))
ZipList' (Cons 10 (Cons 108 (Cons 100 (Cons 13 (Cons 5 Nil)))))

The result should be a ZipList of 10, 108, 5 -- but somehow 100 and 13 are crashing the party.

So I tried pulling my function out of the instance so that I could inspect the type that Haskell infers:

(<**>) (ZipList' Nil) _ = ZipList' Nil
(<**>) _ (ZipList' Nil) = ZipList' Nil
(<**>) (ZipList' (Cons f fs)) (ZipList' (Cons x xs)) =
  ZipList' $ Cons (f x) (fs <**> xs)

but it won't compile!

17-applicative/list.hs:94:26: error:
    • Couldn't match expected type ‘ZipList' (a0 -> b0)’
                  with actual type ‘List (a -> b)’
    • In the first argument of ‘(<**>)’, namely ‘fs’
      In the second argument of ‘Cons’, namely ‘(fs <**> xs)’
      In the second argument of ‘($)’, namely ‘Cons (f x) (fs <**> xs)’
    • Relevant bindings include
        xs :: List a (bound at 17-applicative/list.hs:93:49)
        x :: a (bound at 17-applicative/list.hs:93:47)
        fs :: List (a -> b) (bound at 17-applicative/list.hs:93:26)
        f :: a -> b (bound at 17-applicative/list.hs:93:24)
        (<**>) :: ZipList' (a -> b) -> ZipList' a -> ZipList' b
          (bound at 17-applicative/list.hs:91:1)

The error tells me that I'm trying to pass a List where a ZipList is expected, which I can see. But how then did my Applicative instance even compile?

Aaron
  • 15
  • 7
  • 3
    Aside: to be law-abiding, `pure` for `ZipList` should return an infinite list of its argument, not a singleton list. – Jon Purdy May 17 '18 at 01:18

1 Answers1

5

The problem is the <*> in ZipList' $ Cons (f x) (fs <*> xs).

It's not ZipList''s <*>, it's List's.

Try ZipList' $ Cons (f x) (case ZipList' fs <*> ZipList' xs of ZipList ys -> ys) `

rampion
  • 87,131
  • 49
  • 199
  • 315