Want to keep learning?

This content is taken from the The University of Glasgow's online course, Functional Programming in Haskell: Supercharge Your Coding. Join the course to learn more.

Skip to 0 minutes and 4 seconds JEREMY: Functional programming languages have a reputation for being complex. This is probably deserved, but it’s off-putting to novice programmers. One of the most intimidating features about Haskell is monads. In this video we’re going to delve into them in more detail to try and understand what monads are really all about. Firstly, cue some relaxing music.

Skip to 0 minutes and 38 seconds Now let’s start off with the following high level definition. Monads allow sequencing of function calls to be enforced by the type system. Is that enough? Well, perhaps it’s enough to be getting on with for now. Monads allow computations to be chained together. Effectively, a monad is a computation pattern as Katie from Facebook told us last week. To reassure you further, we’ve already encountered at least two examples of monads on the course. The IO monad. In week two of the course we studied IO actions like putStrLn and getLine. We looked at the do construct for sequencing these actions, so the result of one IO action could become the input of a subsequent IO action. For example, look at this code.

Skip to 1 minute and 39 seconds This is a use of the IO monad wrapped up as a do block. Secondly, the maybe monad. In week three of the course we studied maybe values, which could be Just x or Nothing. These are used to represent values from computations that may fail. Again, we can use do blocks to order a sequence of computations on maybe values. This is the maybe monad. Look at this block. What value does it return?

Skip to 2 minutes and 24 seconds Note that the return keyword here put the final computed value in an appropriate context. More details in the next step. Here’s another do block.

Skip to 2 minutes and 39 seconds What value does it return? The Nothing value propagates through the do block and is returned. We are going to investigate the properties of monads over the next few steps on the course to try and understand them in some more detail. However, I hope it’s moderately reassuring to realize that we’ve already encountered monads in Haskell and understood them at some level.

We Already Know About Monads

Monads, as a concept, cause trouble to some novice Haskell programmers. How and why do we need to understand this abstract mathematical formalism?

Over the next few steps, we are going to explore monads in some detail. For now, we want to reassure you that we have already used monads — for input/output and Maybe values.

Share this video:

This video is from the free online course:

Functional Programming in Haskell: Supercharge Your Coding

The University of Glasgow

Get a taste of this course

Find out what this course is like by previewing some of the course steps before you join: