4 ms·
That's pretty much the point. I'll detail the first example (the Maybe monad). The idea is that you have a maybe object that is either an just an object (denot
by Davidbrcz 9y ago
That's pretty much the point. I'll detail the first example (the Maybe monad).
The idea is that you have a maybe object that is either an just an object (denoted Just(a)) or nothing at all (denoted Nothing).
If you want to manually apply a function f on object m, the code would look like this
if(m is Just(a)){
f(a)
} else{
// there is nothing to do
}
You can take f as a parameter to create a generic function apply. You want to your new function to be total (to return a value in all cases). Since you may (or may not) have a value within the maybe monad, the return type is also a Maybe value. If there was no value, then return Nothing, else apply `f` on `a` and wrap it back within the JUst part of the monad. The code looks like this.
apply(m,f){
if(m is Just(a)){
return Just(f(a))
} else{
return Nothing.
}
}
From an initial maybe value m, you can chain calls:
apply(apply(apply(m,f),g),h)
With a bit of syntactic sugar, the code looks like this.
do
m <- getData
b <- f a
c <- g b
d <- h c
print d
And the code is similar for the others cases. In all solutions, <- denotes an apply function on some monad.
There is a function for each type of monad and it is responsible for doing all repetitive plumbing according to the given type of the monad.
I hope it helps =)
- vesak 9y agoYou (and the other repliers) seem to be confused. It's not that I don't understand monads, it's that I don't value them. It seems obvious to me that they serve mostly to harm code quality.