Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do the functor laws prove complete preservation of structure?

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?

like image 653
kqr Avatar asked May 15 '14 10:05

kqr


People also ask

Why set is not a functor?

Mapping a set doesn't preserve those structures, and that's the reason that sets aren't functors.

Why are functors important?

Functors are also important because they are a building block for applicatives and monads, which are coming in future posts.

What is functor in programming?

In functional programming, a functor is a design pattern inspired by the definition from category theory, that allows for a generic type to apply a function inside without changing the structure of the generic type. This idea is encoded in Haskell using type class.

Is a functor a Monad?

A functor takes a pure function (and a functorial value) whereas a monad takes a Kleisli arrow, i.e. a function that returns a monad (and a monadic value). Hence you can chain two monads and the second monad can depend on the result of the previous one.


1 Answers

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.

like image 138
fizruk Avatar answered Sep 17 '22 12:09

fizruk