我试图为我的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)
对于长度为1或2的ZipLists,它按预期工作:
> ZipList' (Cons (*2) (Cons (+9) Nil)) <*> ZipList' (Cons 5 (Cons 9 Nil))
ZipList' (Cons 10 (Cons 18 Nil))
但是当我去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)))))
结果应该是一个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)
但它不会编译!
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)
该错误告诉我,我正在尝试传递一个预期有ZipList的List,我可以看到。但是,我的Applicative实例如何编译呢?
答案 0 :(得分:5)
问题是<*>
中的ZipList' $ Cons (f x) (fs <*> xs)
。
它不是ZipList'
&#39; <*>
,List
。
试试ZipList' $ Cons (f x) (case ZipList' fs <*> ZipList' xs of ZipList ys -> ys)
`