3 ms·
E.g. Functor is just like template in C++ for constructing type. No, a type variable is! For instance, if we have a data type: data MyBox a = MyBox a a is
by danieldk 13y ago
E.g. Functor is just like template in C++ for constructing type.
No, a type variable is! For instance, if we have a data type:
data MyBox a = MyBox a
a is the type variable, and is pretty much the same thing as a C++ class or struct template that stores a (const) value:
template <class T>
struct MyBox {
MyBox(T const &nv) : v(nv) {}
T const v;
};
This has nothing to do with functors (yet). MyBox has a so-called kind of
MyBox :: * -> *
meaning that MyBox takes a type (namely a) and returns a type. For instance, MyBox Int has the kind:
MyBox Int :: *
Now, a Functor is any data type of kind
* -> *
for which we can implement the function fmap
fmap :: (a -> b) -> f a -> f b
Such that:
fmap id = id
fmap (p . q) = (fmap p) . (fmap q)
hold. We can implement this function for MyBox and show that the laws hold (left as an exercise to the reader):
instance Functor MyBox where
fmap f (MyBox v) = MyBox (f v)
In other words, fmap applies a function within a context. And the fact that a particular context (such as MyBox) is a Functor states that the functor laws hold.