how do I abstract this pattern ?

Daniel Fischer daniel.is.fischer at web.de
Wed May 21 12:57:01 EDT 2008


Am Mittwoch, 21. Mai 2008 18:31 schrieb Bulat Ziganshin:
> Hello HP,
>
> Wednesday, May 21, 2008, 8:11:56 PM, you wrote:
> > Suppose p1, p2, p3 are 3 predicates
> > that take an input -- say, a String.
> > They return either (True, result)
> >             or     False.
>
> impossible because these are different types :))
>
> if they return Just result or Nothing - yes, use Maybe as monad:
>
> combine p1 p2 p3 x= do x1 <- p1 x
>                        x2 <- p2 x1
>                        x3 <- p3 x2
>                        return x3
>
> or shortly
>
> combine p1 p2 p3 x   =   p1 x >>= p2 >>= p3

Actually, (s)he wanted a sort of catch chain, so

import Control.Monad  -- for MonadPlus

combine p1 p2 p3 x = p1 x `mplus` p2 x `mplus` p3 x

or 

combine ps x = msum $ map ($ x) ps

or just

case p1 x of
	Just r -> return r
	Nothing -> case p2 x of
			Just r -> return r
			Nothing -> ...



More information about the Glasgow-haskell-users mailing list