1
votes

I have a monadic function which returns a user id:

do
 id <- getUserId

I need to be able to "superimpose", on getUserId, a function which looks up, and returns, an alias to the value returned by getUserId

Clearly I could write a specific function getAlias and rewrite the monad itself:

do
 id <- getAlias getUserId

However I feel that this can be done more generally, reusably and invisibly, by hiding getAlias in the bind function of a monad.

Do Monad Transformers perform this function, i.e. composing the bind function of the inner monad with a bind function of the outer monad? Or do I need some other control structure here?

1
Can you clarify a bit what getAlias is doing? I don't think monad transformers are going to be helpful here, but it's hard to tell exactly what to suggest instead without a bit more information.Daniel Wagner
If you give the types of getUserId and getAlias it will be very helpful, for example.Chris Taylor
The context is that getUserId :: SomeType IDX, and getAlias :: SomeType IDX -> SomeType IDY. getUserId looks up a value in a database and packs it into SomeType IDX. getAlias takes that value, looks up an alias in a database, and returns that value.Robert Onslow
I guess the question in its most general form is how to compose 2 different monads so that their bind functions are automatically composed togetherRobert Onslow
That's impossible in full generality. Monad transformers do it in specific cases, but you can't do it in general.Louis Wasserman

1 Answers

1
votes

I don't really think you can get much lighter-weight than function application here. To answer your direct questions:

  1. Yes, monad transformers combine the bind functions of the transformer and the underlying monad.
  2. No, in general, you cannot combine two monad's bind functions and produce the bind function of another monad.

But I don't think either of those two direct answers matter, since getAlias isn't likely to be the bind of any law-abiding monad. (At the very least, bind functions must be very polymorphic, which getAlias isn't!).