Do the functor laws prove complete preservation of structure?

不打扰是莪最后的温柔 提交于 2019-12-10 12:52:13

问题


In the documenation for Data.Functor the following two are stated as the functor laws, which all functors should adhere to.

fmap id  ==  id
fmap (f . g)  ==  fmap f . fmap g

The way my intuition tells me functors should work is that they should be "structure preserving", or in other words, if you have a function f :: a -> b and it's inverse g :: b -> a then

fmap f . fmap g  ==  id

I have not been able to come up with an implementation of fmap that would adhere to the first two laws and violate the second, but that's hardly proof. Can someone enlighten me?


回答1:


Actually, your "third" functor law follows directly from actual functor laws and the fact that f . g ≡ id:

fmap f . fmap g ≡ fmap (f . g) ≡ fmap id ≡ id

And there's more: Haskell ensures that if first law holds for Functor instance, then the second one also holds (this is a free theorem for the type of fmap). I.e. you have to prove only fmap id ≡ id law for your Functor instance to ensure that it is valid.



来源:https://stackoverflow.com/questions/23675434/do-the-functor-laws-prove-complete-preservation-of-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!