需要什么才能让我的自定义ZipList应用程序实例进行编译?

时间:2016-03-14 18:08:23

标签: haskell applicative

这是我用于创建自定义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'...

1 个答案:

答案 0 :(得分:5)

您的go需要ZipList作为输入,但(<*>) fs xs xsfsZipList'。你应该打开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

作为一般规则,您应该避免使用headtail和其他部分函数(即可能抛出异常的函数)。 Cons x xs上的模式匹配会绑定头部和尾部,因此此后headtail没有太大用处。使用部分功能是非常罕见的。