rob-brown / MonadEx

Upgrade your pipelines with monads.
MIT License
306 stars 13 forks source link

Example of composing monads? #9

Closed beezee closed 6 years ago

beezee commented 6 years ago

My experience in other languages that support monads, is that you need a transformer to compose monads (eg MaybeT would allow you to cut through a Maybe inside another Monad by wrapping the whole thing in the transformer.)

I tried some time ago to implement transformers for MonadEx, and I hit a wall I believe attempting to represent a higher-kinded type (MaybeT would take some monad, without the contents known, so like MaybeT[Reader[_], A], rather than MaybeT[Reader[X], A].) Sorry if this sounds off, it was a pretty long time ago and I unfortunately didn't save my progress.

Anyway all of that said, my question comes back to the README for MonadEx. There's a heading that talks briefly about composing monads, but no example. Can you clarify how you would go about doing this in Elixir using this lib?

rob-brown commented 6 years ago

I never got too far into monad transformers, so I can't say much about them.

When I was talking about composing monads my intent was that the contents are known. Since the contents are known, it's trivial to destructure the monads.

Here's an example. Let's say you want to use a writer monad to keep a log and the value of the writer may or may not be present. So, the writer monad would wrap a maybe monad.

wrapped = 42 |> Monad.Maybe.some |> Monad.Writer.writer
value = wrapped |> Monad.Writer.runWriter |> elem(0) |> Monad.Maybe.unwrap!

I hope that helps.