Working with option using Maybe Monad
One of the most used type in ReasonML is option
type. It represents the value which can be present( Some(x)
) or absence( None
). This type is very troublesome to whom has not used to strongly typed language because it will reject any incorrect program.
Snippet below shows how we can work with option
using a pattern matching.
Pattern matching is very powerful and convenient. However, when you want to chain values, it might make code very hard to read.
Suppose we want to create a program that read three pieces of information from remote API. Each API call returns an option
value, which can be None
if there is no data.
The program should fail and stop work when any of the data is not available. If we want to write that in Pattern matching style, we would end up the code similar to that shown below.
Someone might feel familiar with this code style, especially, one who works with Promise
in JavaScript. The code returns "No data"
and stops the execution when any of data in the chain is None
. The difference to Promise
is that this code is synchronous.
Now, let us try Monad style for the same program. First, we must define a monad module which contains return
and >>=
(bind) function.
Function return
is merely put a
of type 'a
in Some
. The function that does all the job is >>=
. This function takes value from previous option
and take out the value inside, send it into function f
.
This code, as you can see, is easier to read. The result of the code and execution path is the same. the function will stop soon as it reaches any point in the chain with no data.
Monad is considered one of the most powerful ideas in the modern functional programming. It can be used to “box” any execution context, which, as a result, makes the easier to debug and to reason about.