Alex Rivera | Logout

How do functors work in haskell?

Asked 2012-10-30T08:00:13.763
60

I'm trying to learn Haskell and I'm through all the basics. But now I'm stuck, trying to get my head around functors.

I've read that "A functor transforms one category into another category". What does this mean?

I know it's a lot to ask, but could anyone give me a plain english explanation of functors or maybe a simple use case?

Edit
Report

1 Answer

15

It's important to keep separate in your head the distinction between a functor itself, and a value in a type which has a functor applied to it. A functor itself is a type constructor like Maybe, IO, or the list constructor []. A value in a functor is some particular value in a type with that type constructor applied. e.g. Just 3 is one particular value in the type Maybe Int (that type is the Maybe functor applied to the type Int), putStrLn "Hello World" is one particular value in the type IO (), and [2, 4, 8, 16, 32] is one particular value in the type [Int].

I like to think of a value in a type with a functor applied as being "the same" as a value in the base type, but with some extra "context". People often use a container analogy for a functor, which works pretty naturally for quite a few functors but then becomes more of a hindrance than a help when you're having to convince yourself that IO or (->) r is like a container.

So if an Int represents an integer value, then a Maybe Int represents an integer value that may not be present ("may not be present" is the "context"). An [Int] represents an integer value with a number of possible values (this is the same interpretation of the list functor as the "nondeterminism" interpretation of the list monad). An IO Int represents an integer value whose precise value depends on the entire universe (or alternatively, it represents an integer value that can be obtained by running an external process). A Char -> Int is an integer value for any Char value ("function taking r as an argument" is a functor for any type r; with r as Char (->) Char is the type constructor which is a functor, which

answered 2012-10-31T00:27:34.713

Your Answer