Functors
Functors
Recall: A functor is something we can map
over, applying a function to some underlying value.
Now that you know about type classes, classes, and collections, let's talk about how functors really work.
Maybe Functor
Let's go back to the Maybe
example, and see how we could implement it as a functor.
If we have a Just(value)
, we should apply the function to value
:
If we have a None
, we should do nothing
Putting these together:
BTree
As promised, let's go over how to turn a BTree into a functor:
When we call map
on a Node, we want to apply a function to the value, and all values on the left and right.
When we call map
on a Leaf, we want to do nothing. Exactly the same as calling None.map(f)
So, this isn't done automatically, but it's very simple to implement. And now, for any BTree we define, we can call map
on it! Magical!