Search code examples
functional-programmingmonadsfunctor

What is the difference between a Functor and a Monad?


There are similar questions here but they are attached to a particular programming language and I am looking for an answer on the conceptual level.

As I understand, Functors are essentially immutable containers that expose map() API which derives another functor. Which addition makes it possible to call a particular functor a monad?

As I understand, every monad is a functor but not every functor is a monad.


Solution

  • (Note that this will be a simplified explanation for category theory concepts)

    Functor

    A Functor is a function from a set of values a to another set of values: a -> b. For a programming language this could be a function that goes from String -> Integer:

    function fn(text: string) : integer

    Composition

    Composition is when you use the value of one function as input to the value of the next: fa(fb(x)). For example:

    hash(lowercase(text))

    Monads

    A Monad allows to compose Functors that either are not composable otherwise, compose Functors by adding extra functionality in the composition, or both.

    • An example of the first is a Monad for a Functor String -> (String, Integer)

    • An example of the second is a Monad that counts the Number of functions called on a value

    A Monad includes a Functor T that is responsible for the functionality you want plus two other functions:

    • input -> T(input)
    • T(T(input)) -> T(input)

    The first function allows to transform your input values to a set of values that our Monad can compose. The second function allows for the composition.

    So in conclusion, every Monad is not a Functor but uses a Functor to complete it's purpose.