用函数实现Newtype的Functor实例

时间:2014-12-27 05:14:09

标签: haskell

鉴于以下newtype

newtype Bar a = Bar { foo :: Int -> a }

我尝试为它定义一个Functor实例。

instance Functor (Bar) where
    fmap g (Bar f) = Bar $ fmap f 

我打算将Int -> a映射到Int -> b - 我认为这是正确的结果类型。

但是,我收到了编译时错误:

Couldn't match type `f0 Int' with `Int' 
Expected type: Int -> f0 a   
Actual type: f0 Int -> f0 a In the second argument of `($)', namely `fmap f' 
In the expression: Bar $ fmap f

如何实现此Functor实例?

1 个答案:

答案 0 :(得分:7)

应该是

instance Functor Bar where
    fmap g (Bar f) = Bar $ fmap g f

我想你可能错过了g。您看到f0 Int -> f0 a因为f :: Int -> a所以fmap f :: Functor f0 => f0 Int -> f0 a。自g :: a -> b起,您希望fmap g超过f,以便fmap g f :: Int -> b

相关问题