Keeping with our series of posts about using the Either Monad in various ways:
This time, I expand from Either to EitherT, which allows us to interleave an outer monad with an inner one.
When we call
runEitherT with a
do block, we are making a new context, where
we make an EitherT type, wrapped around an inner IO type. I am not sure what
the exact type there is, I’ll have to look into that later.
Control.Monad.Trans to get access to the
lift function. That lets
us go down a layer into that EitherT wrapped around the IO to run IO commands.
You can see how in the workflow of the EitherT section, it asks for some text, does some “work” that may fail, and then asks for the next bit of text to work on.
The coolest part is that if the first bit fails, it bails out of the whole
workflow with the correct
Left value, not even asking for the second bit
The only other gotcha is that
EitherT isn’t quite the same as a normal
Either type, so you have to use functions to convert between them.
hoistMaybe take a normal version of
Either/Maybe and turn it
Similarly, we had to use
noteT instead of
note. Same behavior, but it just
works on the transformed versions of the types.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39