用函数实现Newtype的Functor实例

Kev*_*ith 1 haskell

鉴于以下内容newtype:

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

我试图Functor为它定义一个实例.

instance Functor (Bar) where
    fmap g (Bar f) = Bar $ fmap f 
Run Code Online (Sandbox Code Playgroud)

我打算映射Int -> a到get 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
Run Code Online (Sandbox Code Playgroud)

我该如何实现这个Functor实例?

bhe*_*ilr 7

它应该是

instance Functor Bar where
    fmap g (Bar f) = Bar $ fmap g f
Run Code Online (Sandbox Code Playgroud)

我想你可能刚刚错过了g.你f0 Int -> f0 af :: Int -> a这样看的fmap f :: Functor f0 => f0 Int -> f0 a.因为g :: a -> b,你要fmap g过度f使fmap g f :: Int -> b.

  • 或者只是`实例Functor Bar,其中fmap f(Bar g)= Bar(f.g)` (5认同)