Combining Maybe and Either monads
While writing a function to generate a look at matrix I came across this problem where I had to combine two monads, a Maybe and an Either. I struggled for a while to find out how I could connect the two bits together then just wrote a function to transform from Maybe to Either. I didn't like it, and was sure there was a much more elegant way to do this.
Fortunately my brother is a CTO with around ten years of production Haskell experience and I'm very lucky to be able to ask him questions about Haskell. He's also the reason I'm even doing Haskell in the first place. Thanks brother for putting up with all my questions and for showing me this amazing language!
So here's my original implementation, ended up doing a lot of fmapping and apping. I knew I could use something like liftA3 or similar but that's where I left the exercise at.
Here's the version after going over it with my brother. A dramatic improvement, and I could get rid of two redundant error cases one of which I had to add for my transformation from Maybe to Either. So the beauty of the new implementation is the computation easily short circuits on an error.
I'm really loving the expressive and declarative nature of Haskell. It's really easy to read the flow of code - it basically comments itself.