![](/img/trans.png)
[英]How to write map/fmap analogue (a->b) -> F m a -> F m b
[英]Is (fmap f) the same as (f .) if f is a function of type a->b?
我正在嘗試實現一個Functor實例
data ComplicatedA a b
= Con1 a b
| Con2 [Maybe (a -> b)]
對於Con2,我的思維過程是fmap需要的東西
fmap f (Con2 xs) = Con2 (map f' xs)
然后我需要有一個列表映射函數f'
Maybe (a -> x) -> Maybe (a -> y)
由於Maybe
是一個Functor,我可以像f'一樣寫
fmap ((a->x) -> (a->y))
為了獲得((a->x) -> (a->y))
,我想我可以做fmap (x->y)
,它與(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)
((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)
我只是想知道我的思維過程和解決方案是什么問題。 如果f是a-> b類型的函數,則(fmap f)與(f。)相同嗎?
先感謝您。
解決方案確實是等同的。 函數/ reader函子的fmap
是(.)
:
instance Functor ((->) r) where
fmap = (.)
( (->) r
是與前綴語法一起使用的函數類型構造函數 - (->) ra
與r -> a
相同。)
直覺是,如你所知, (.) :: (x -> y) -> (a -> x) -> (a -> y)
使用x -> y
函數來修改結果a -> x
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.