Haskell ZipList Applicative

Aar*_*ron 1 haskell typeclass applicative

我正在尝试为我的ZipList编写一个Applicative实例,我收到了一些令人困惑的结果.

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)
Run Code Online (Sandbox Code Playgroud)

对于长度为1或2的ZipLists,它可以正常工作:

> ZipList' (Cons (*2) (Cons (+9) Nil)) <*> ZipList' (Cons 5 (Cons 9 Nil))
ZipList' (Cons 10 (Cons 18 Nil))
Run Code Online (Sandbox Code Playgroud)

但是当我去3+时,我会得到一些奇怪的结果:

> 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)))))
Run Code Online (Sandbox Code Playgroud)

结果应该是一个10,108,5的ZipList - 但不知何故100和13正在崩溃党.

所以我尝试将我的函数拉出实例,以便我可以检查Haskell推断的类型:

(<**>) (ZipList' Nil) _ = ZipList' Nil
(<**>) _ (ZipList' Nil) = ZipList' Nil
(<**>) (ZipList' (Cons f fs)) (ZipList' (Cons x xs)) =
  ZipList' $ Cons (f x) (fs <**> xs)
Run Code Online (Sandbox Code Playgroud)

但它不会编译!

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)
Run Code Online (Sandbox Code Playgroud)

该错误告诉我,我正在尝试传递一个List,其中ZipList是预期的,我可以看到.但是,我的Applicative实例如何编译?

ram*_*ion 5

问题是<*>ZipList' $ Cons (f x) (fs <*> xs).

这不是ZipList'<*>,它是List的.

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