Monads

By Lups

Introduction

Welcome, today I'll be talking about monads, a functional programming concept (there's also an algebra concept called "monad").

In languages like C, we can easily get user input using:

#include <stdio.h>

int main() {

    int age;
    printf("Enter your age: ");
    scanf("%d", &age);  
    printf("You have %d years old\n", age);
    return 0;
}

The C program will first print "Enter your age: ", and then wait for user input, after the user input is received, it will print the input.

Pretty simple huh?

But in functional languages like Haskell (the language we are going to use as example), it ain't that easy. That's because Haskell uses multithreading to run expressions, so, at the same time it gets user input, it prints its output. In order to prevent that, monad were created.

Monad

History

The history of monad starts in 1950, when the mathematician Roger Godement was the first one to come up with the term "monad". The Monad came to functional programming when the computer scientist Eugenio Moggi linked algebraic Monads with functional programming. Since then, Monad has been used in many occasions, but this article focuses on the funcitonal programming monad.

Definition

Monad make each function run after another, instead of running simultaneously. Let's take a look at an example:

main :: IO ()
main = putStr "What is your age? "
    >> getLine
    >>= \age -> putStrLn ("You're " ++ age ++ " years old")

The >> and >>= operators are commonly called bind operators in Haskell (they are different from the logical shift operators talked in the last article). The >> is used to sequence and ignore the internal value of the monad on the left. The >>= is used to sequence and run the function on the right.

Monad rules

Monad have three rules (also called laws):

Left identity: return a >>= h ≡ h a
Right identity: m >>= return ≡ m
Associativity: (m >>= g) >>= h ≡ m >>= (\x -> g x >>= h)

But what does this rules means?

Well, the left identity states that if we put a default context with return into a value and handle it to a function by using >>=, it's the same as taking a value and apply a function to it.

The right identity states that if we have a monad value and we use the >>= to handle it to a function, it will be equal to the same monadiac value.

The Associativity states that when we have a chain of monadic function applications that uses >>=, it shouldn't matter how it's nested.

Conclusion

This paper was an introduction to the functional programming concept monad, I hope you could learn something from it, any doubts, feel free to contact me at [email protected].

See more

Comonad

Monad laws

All about monads