Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What is a Haskell monad?

Zain Babar


A monad is a mathematical term. A computation builder is another term for a monad. A monad is used for chaining operations. This means that a monad is used to chain different operations in a certain way that can then be performed on the input.


A monad doesn’t always simplify things. It is just another way to chain operations. In most cases, it makes the chaining more complex.

To learn more about monads, click on the following link.


Problem statement

Increment all the elements in the following list by 1 and remove the integer 4, if present.

We use a bind operator >>= to write code in Haskell. It has the same function as a map function when used with lists. It performs a certain operation on every element of a list. However, it has different functionalities for different types.

Code example

increment(h:b)=  (h:b) >>= (\x -> [x+1] >>= (\y -> if y == 4 then [] else [y] ))
main= print(increment[1,2,3,4,5])

However, Haskell has a specific syntax for monads. Instead of using the bind operator, Haskell makes use of a do block. The constraint of every operation of the same type still remains.

increment (h:b)= do {x <- (h:b)
                    ;y <- [x+1]
                    ;if y == 4 then [] else [y]} 

Code explanation

In the code above, <- might look like an assignment operator, but it is actually similar to the bind operator mentioned above. This means that if there is a list on the right side of this operator, there will be an integer on the left side, but it will execute for every single element of the list.


Haskell has some built-in support for the patterns due to which we can hide operators like bind and other parts. These patterns also help us from repeating the code. It also helps separate the desirable code from the undesirable code. It also has an embedded parser and allows the addition of GOTO to the language.



View all Courses

Keep Exploring