Im trying to understand what a functor is, i found this tutorial/example:
http://en.wikibooks.org/wiki/Haskell/Solutions/Applicative_Functors
data Tree a = Node a [Tree a]
The functor for the above type being:
instance Functor Tree where
fmap f (Node a ts) = Node (f a) (map (fmap f) ts)
could someone help explain what exactly they have done and why they have done it? My understanding is that a functor allows you to iterate over a data type. I cant seem to understand the syntax used though?
A
Functoris useful for mapping between two data representations. Sometimes that might resemble iteration, sometimes not. Having this commonFunctortypeclass allows us to ignore the actual structure of the data type (Maybe,List,Tree) and focus only on the data they contain. The author of that data type should know how that data structure might be traversed/iterated so he should provide the implementation for that (in the form of aFunctorinstance of that data type). All we have to provide is that functionfwhich takes anaand maps it to ab. For example:We were able to lowercase those chars using the same code
toLowercombined withfmap.So, what you should do when defining that
Functorinstance is to extract inner data using pattern matching, and the apply the received callback functionfto each of these results.An infix synonym for
fmapcan be found in theControl.Applicativemodule, called<$>.