[Haskell-cafe] Conversion between MonadPlus instances

Andrew Pimlott andrew at pimlott.net
Fri Jul 1 14:42:08 EDT 2005


On Fri, Jul 01, 2005 at 12:33:13PM +0200, Gracjan Polak wrote:
> Example: I have some function, that can return multiple results. 
> Currently I need only the first one, but in the spirit of NotJustMaybe, 
> I try to be as general as possible.
> 
> If I code it like this:
> 
> reduction :: (MonadPlus m) => [Rule] -> Expr -> m Expr
> reduction expr = do
>     rule <- rules
>     reduction rule expr
> 
> Variable m gets unified with []. But I want m to stay as general as 
> possible here.
> 
> This version works, but I somehow do not like the "smell" of it
> 
> reduction expr = do
>     let listmonad = do
>         rule <- rules
>         reduction rule expr
>     msum (map return listmonad)
> 
> Is there a better way how to "embed" MonadPlus in other "MonadPlus"?

It might smell better if you wrote it as

    reduction expr = do
        rule <- msum (map return rules)
        reduction rule expr

or made a separate function

    msumVals :: MonadPlus => [a] -> m a
    msumVals xs = msum (map return xs)

But I think you have a further problem, because the type you gave for
reduction does not match your definitions.  And if it did, I think you
would shortly run into another problem, involving infinite types.  Maybe
you're thinking along the lines of

    reduction rules expr = do
        rule <- msumVals rules
        rules' <- run rule
        reduction rules' expr

for some suitable function run?

Andrew


More information about the Haskell-Cafe mailing list