[英]Implement Functor Instance for Newtype with Function
Given the following newtype
: 鉴于以下newtype
:
newtype Bar a = Bar { foo :: Int -> a }
I tried to define a Functor
instance for it. 我试图为其定义一个Functor
实例。
instance Functor (Bar) where
fmap g (Bar f) = Bar $ fmap f
I intended to map over Int -> a
to get Int -> b
- I think that's the correct resultant type. 我打算将Int -> a
映射为Int -> b
我认为这是正确的结果类型。
However, I got the compile-time error: 但是,我得到了编译时错误:
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
How can I implement this Functor
instance? 如何实现此Functor
实例?
It should be 它应该是
instance Functor Bar where
fmap g (Bar f) = Bar $ fmap g f
I think you might have just missed the g
. 我认为您可能刚刚错过了g
。 You see f0 Int -> f0 a
because f :: Int -> a
so fmap f :: Functor f0 => f0 Int -> f0 a
. 您看到f0 Int -> f0 a
fmap f :: Functor f0 => f0 Int -> f0 a
f0 Int -> f0 a
因为f :: Int -> a
fmap f :: Functor f0 => f0 Int -> f0 a
f :: Int -> a
so fmap f :: Functor f0 => f0 Int -> f0 a
。 Since g :: a -> b
, you want to fmap g
over f
so that fmap gf :: Int -> b
. 由于g :: a -> b
fmap g
g :: a -> b
,因此您想在f
上fmap g
,以便fmap gf :: Int -> b
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.