可以部分使用函子吗

时间:2019-04-16 06:28:14

标签: haskell types functor

我正在尝试为以下类型实现fmap

data Tree a = Leaf a | Node a (Tree a) (Tree a) | Empty deriving (Eq,Show)
instance Functor Tree where
        fmap _ Empty=Empty
        fmap f (Leaf x)=Leaf (f x)
        fmap f (Node t left right)=Node (f t) left right

我不断收到类型不匹配错误:

错误

* Couldn't match type `a' with `b'
      `a' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a b. (a -> b) -> Tree a -> Tree b
        at Monad.hs:8:9-12
      `b' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a b. (a -> b) -> Tree a -> Tree b
        at Monad.hs:8:9-12
      Expected type: Tree b
        Actual type: Tree a

为什么会出现此错误,但是当我还将fmap应用于子节点时,它也会毫无问题地进行编译:

fmap f (Node t left right) = Node (f t) (fmap f left) (fmap f right)

这是否意味着a内的所有Tree-s必须以某种方式变为b-s?我只在第一种情况下与非功能者打交道?                        ^

1 个答案:

答案 0 :(得分:8)

  

这是否意味着a内的所有Tree-s必须以某种方式变为b-s?我只在第一种情况下与非功能者打交道? ^

是的,没错。您正在尝试实现fmap :: (a -> b) -> Tree a -> Tree b,但是在编写时:

fmap f (Node t left right) = Node (f t) left right

您正在尝试使用参数Node :: b -> Tree b -> Tree b -> Tree bf t :: bleft :: Tree a来调用right :: Tree a。将Tree a转换为Tree b的唯一方法是通过fmap f :: Tree a -> Tree b,这就是为什么:

fmap f (Node t left right) = Node (f t) (fmap f left) (fmap f right)

按预期工作。