如果f是类型a-> b的函数,(fmap f)是否与(f.)相同? [英] Is (fmap f) the same as (f .) if f is a function of type a->b?

查看:88
本文介绍了如果f是类型a-> b的函数,(fmap f)是否与(f.)相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现

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 ar -> 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.)相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆