这是我用于创建自定义ZipList类的自定义List类。我想创建一个ZipList的应用实例。
import Control.Applicative
data List a =
Nil
| Cons a (List a)
deriving (Eq, Show)
instance Functor List where
fmap f (Cons x xs) = Cons (f x) (fmap f (Cons (head' xs) (tail' xs)))
fmap _ Nil = Nil
instance Applicative List where
pure x = Cons x Nil
(<*>) fs xs = Cons (head' fs $ head' xs) ((<*>) (tail' fs) (tail' xs))
head' :: List a -> a
head' (Cons a _) = a
tail' :: List a -> List a
tail' (Cons _ l) = l
take' :: Int -> List a -> List a
take' 0 _ = Nil
take' _ Nil = Nil
take' i xs = Cons (head' xs) (take' (i-1) (tail' xs))
newtype ZipList' a =
ZipList' (List a)
deriving (Eq, Show)
instance Functor ZipList' where
fmap f (ZipList' xs) = ZipList' $ fmap f xs
instance Applicative ZipList' where
pure x = ZipList' (Cons x Nil)
(<*>) fs xs = ZipList' (go fs xs)
where go gs ys = Cons (head' gs $ head' ys) (go (tail' gs) (tail' ys))
go Nil _ = Nil
go _ Nil = Nil
我得到的错误是:
chap17/ZipList_applicative.hs:38:30: Couldn't match expected type ‘List (r0 -> b)’ …
with actual type ‘ZipList' (a -> b)’
Relevant bindings include
xs :: ZipList' a
(bound at /Users/ebs/code/haskell/book/chap17/ZipList_applicative.hs:38:12)
fs :: ZipList' (a -> b)
(bound at /Users/ebs/code/haskell/book/chap17/ZipList_applicative.hs:38:9)
(<*>) :: ZipList' (a -> b) -> ZipList' a -> ZipList' b
(bound at /Users/ebs/code/haskell/book/chap17/ZipList_applicative.hs:38:3)
In the first argument of ‘go’, namely ‘fs’
In the first argument of ‘ZipList'’, namely ‘(go fs xs)’
chap17/ZipList_applicative.hs:38:33: Couldn't match expected type ‘List r0’ …
with actual type ‘ZipList' a’
Relevant bindings include
xs :: ZipList' a
(bound at /Users/ebs/code/haskell/book/chap17/ZipList_applicative.hs:38:12)
fs :: ZipList' (a -> b)
(bound at /Users/ebs/code/haskell/book/chap17/ZipList_applicative.hs:38:9)
(<*>) :: ZipList' (a -> b) -> ZipList' a -> ZipList' b
(bound at /Users/ebs/code/haskell/book/chap17/ZipList_applicative.hs:38:3)
In the second argument of ‘go’, namely ‘xs’
In the first argument of ‘ZipList'’, namely ‘(go fs xs)’
Compilation failed.
它表示它希望列表(r0 - > b)类型为go,而不是ZipList'。我不明白为什么,go返回一个List,而不是ZipList'...
答案 0 :(得分:5)
您的go
需要ZipList
作为输入,但(<*>) fs xs
xs
和fs
为ZipList'
。你应该打开newtype:
ZipList' fs <*> ZipList' xs = ZipList' (go fs xs)
此外,您的go
错了。每当程序评估任一参数中的空列表时,它都会因运行时错误而失败,因为go gs ys
大小写匹配所有内容,并且后面的大小写无法访问。你应该做这样的事情:
go (Cons f fs) (Cons x xs) = Cons (f x) (go fs xs)
go _ _ = Nil
作为一般规则,您应该避免使用head
,tail
和其他部分函数(即可能抛出异常的函数)。 Cons x xs
上的模式匹配会绑定头部和尾部,因此此后head
和tail
没有太大用处。使用部分功能是非常罕见的。