Monads have a reputation for being difficult to understand, but in this article we will look at a simple Python implementation of a simple monad. This will hopefully give some insight into what monads are all about.

What is a monad

In functional programming, we use functions as our primary building block, and function composition as one of the basic ways to structure our code. By function composition we mean functions that call other functions, like this:

y = str(neg(int(x)))

This composed function takes a string, converts it to an integer, negates it, and converts it back to a string. So the string “1” is converted to “-1”.

But there is a problem. What if our initial string is something like “XYZ”? Then int will throw a ValueError exception because it can’t convert that string to an integer value. We will end up in an exception handler somewhere else in our code, or worse still our program might terminate with an error message. This is exactly the sort unpredictability the functional programming is supposed to solve.

Now imagine if the int function was able to return not only the integer value, but also a flag to say whether the conversion had succeeded or failed. This failed flag could be thought of as a context around the actual data - if the failed flag is false, the data is valid, if the failed flag is true we should ignore the data as it isn’t valid.

Even better, suppose that the neg function could also take account of the context. When it receives a value from the int function, it checks the failed flag. If it is false, neg knows that the data is valid, so it negates the value and returns it with the failed flag set to false. If the failed flag is true, neg doesn’t process the value at all, it just returns a context with None data and the failed flag true.

And, of course, the str function would do exactly the same thing. That means that the composed function above would always return a value. It would never throw an exception. But the value would have a context to say whether it was valid or not.

Unfortunately, the intneg and str functions don’t behave like this. That is where monads come in useful.

A monad is a design pattern that allows us to add a context to data values, and also allows us to easily compose existing functions so that they execute in a context aware manner.

#functional-programming #composition #python #monads #computer-science

Simple Python implementation of a simple Monad
1.45 GEEK