Ber*_*ian 6 haskell types functor
我正在尝试实现fmap
以下类型:
data Tree a = Leaf a | Node a (Tree a) (Tree a) | Empty deriving (Eq,Show)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我不断收到类型不匹配错误:
错误
* 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
Run Code Online (Sandbox Code Playgroud)
为什么会出现此错误,但是当我也将其fmap
应用于子节点时,它会毫无问题地进行编译:
fmap f (Node t left right) = Node (f t) (fmap f left) (fmap f right)
Run Code Online (Sandbox Code Playgroud)
这是否意味着必须a
范围内的所有-s会Tree
以某种方式变为b
-s?我只在第一种情况下与非功能者打交道?^
这是否意味着必须
a
范围内的所有-s会Tree
以某种方式变为b
-s?我只在第一种情况下与非功能者打交道?^
是的,这是正确的。您正在尝试实现fmap :: (a -> b) -> Tree a -> Tree b
,但是在编写时:
fmap f (Node t left right) = Node (f t) left right
Run Code Online (Sandbox Code Playgroud)
你试图调用Node :: b -> Tree b -> Tree b -> Tree b
带参数f t :: b
,left :: Tree a
和right :: Tree a
。将a Tree a
变成a 的唯一方法Tree b
是via fmap f :: Tree a -> Tree b
,这就是为什么这样:
fmap f (Node t left right) = Node (f t) (fmap f left) (fmap f right)
Run Code Online (Sandbox Code Playgroud)
可以正常工作。