[英]Is (fmap f) the same as (f .) if f is a function of type a->b?
I am trying to implement a Functor instance of 我正在尝试实现一个Functor实例
data ComplicatedA a b
= Con1 a b
| Con2 [Maybe (a -> b)]
For Con2, my thought process was the fmap needs to be something like 对于Con2,我的思维过程是fmap需要的东西
fmap f (Con2 xs) = Con2 (map f' xs)
then I need to have a list map function f' like 然后我需要有一个列表映射函数f'
Maybe (a -> x) -> Maybe (a -> y)
Since Maybe
is a Functor, I can write f' like 由于
Maybe
是一个Functor,我可以像f'一样写
fmap ((a->x) -> (a->y))
In order to get ((a->x) -> (a->y))
, I thought I could just do fmap (x->y)
which is the same as (fmap f)
为了获得
((a->x) -> (a->y))
,我想我可以做fmap (x->y)
,它与(fmap f)
相同
So my sulotion was 所以我很闷热
instance Functor (ComplicatedA a) where
fmap f (Con1 x y) = Con1 x (f y)
fmap f (Con2 xs) = Con2 (map (fmap (fmap f)) xs)
However the real solution uses (f .)
instead of (fmap f)
to get ((a->x) -> (a->y))
from x -> y
and it looks like this 然而,真正的解决方案使用
(f .)
代替(fmap f)
((a->x) -> (a->y))
从x -> y
得到((a->x) -> (a->y))
它看起来像这样
instance Functor (ComplicatedA a) where
fmap f (Con1 a b) = Con1 a (f b)
fmap f (Con2 l) = Con2 (map (fmap (f .)) l)
I was just wondering what the problem was with my thought process and solution. 我只是想知道我的思维过程和解决方案是什么问题。 Is (fmap f) the same as (f .) if f is a function of type a->b?
如果f是a-> b类型的函数,则(fmap f)与(f。)相同吗?
Thank you in advance. 先感谢您。
The solutions are indeed equivalent. 解决方案确实是等同的。
fmap
for the function/reader functor is (.)
: 函数/ reader函子的
fmap
是(.)
:
instance Functor ((->) r) where
fmap = (.)
( (->) r
is the function type constructor being used with prefix syntax -- (->) ra
is the same as r -> a
.) (
(->) r
是与前缀语法一起使用的函数类型构造函数 - (->) ra
与r -> a
相同。)
The intuition is that, as you have noted, (.) :: (x -> y) -> (a -> x) -> (a -> y)
uses a x -> y
function to modify the results of an a -> x
function. 直觉是,如你所知,
(.) :: (x -> y) -> (a -> x) -> (a -> y)
使用x -> y
函数来修改结果a -> x
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.