问题描述
我正在尝试实现
data ComplicatedA a b
= Con1 a b
| Con2 [Maybe (a -> b)]
对于Con2,我的思维过程是fmap必须类似于
For Con2, my thought process was the fmap needs to be something like
fmap f (Con2 xs) = Con2 (map f' xs)
然后我需要一个像这样的列表映射函数f'
then I need to have a list map function f' like
Maybe (a -> x) -> Maybe (a -> y)
由于Maybe
是函子,所以我可以像这样写f'
Since Maybe
is a Functor, I can write f' like
fmap ((a->x) -> (a->y))
为了获得((a->x) -> (a->y))
,我以为我可以fmap (x->y)
与(fmap f)
In order to get ((a->x) -> (a->y))
, I thought I could just do fmap (x->y)
which is the same as (fmap f)
所以我的预谋是
instance Functor (ComplicatedA a) where
fmap f (Con1 x y) = Con1 x (f y)
fmap f (Con2 xs) = Con2 (map (fmap (fmap f)) xs)
但是真正的解决方案使用(f .)
而不是(fmap f)
从x -> y
获取((a->x) -> (a->y))
,看起来像这样
However the real solution uses (f .)
instead of (fmap f)
to get ((a->x) -> (a->y))
from x -> y
and it looks like this
instance Functor (ComplicatedA a) where
fmap f (Con1 a b) = Con1 a (f b)
fmap f (Con2 l) = Con2 (map (fmap (f .)) l)
我只是想知道我的思考过程和解决方案出了什么问题.如果f是a-> b类型的函数,(fmap f)是否与(f.)相同?
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?
谢谢.
推荐答案
解决方案的确是等效的. fmap
用于该功能/读者函子是(.)
:
The solutions are indeed equivalent. fmap
for the function/reader functor is (.)
:
instance Functor ((->) r) where
fmap = (.)
((->) r
是用于前缀语法的函数类型构造函数-(->) r a
与r -> a
相同.)
((->) r
is the function type constructor being used with prefix syntax -- (->) r a
is the same as r -> a
.)
直觉是,正如您已经注意到的,(.) :: (x -> y) -> (a -> x) -> (a -> y)
使用x -> y
函数来修改a -> x
函数的结果.
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.
这篇关于如果f是类型a-> b的函数,(fmap f)是否与(f.)相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!