how do I abstract this pattern ?

C.M.Brown cmb21 at kent.ac.uk
Wed May 21 13:00:13 EDT 2008


On Wed, 21 May 2008, HP Wei wrote:

>
> Suppose p1, p2, p3 are 3 predicates
> that take an input -- say, a String.
> They return either (True, result)
>             or     False.
>
> I want to get an effect like in this expression:
>
> case p1 s of
>    (True, r) -> r
>    False -> case p2 s of
>                (True, r) -> r
>                False -> case p3 s of
>                            (True, r) -> r
>                            False -> none
>
> Is this a job for Maybe monad ?
> How do I do that ?
>

I think this is a job for the Either monad:

data Either a b = Left a | Right b

case p1 s of
    (Left (True, r)) -> r
    (Right False) -> case p2 s of
                    (Left (True, r)) -> r
                    (Right False) -> case p3 s of
                            (Left (True, r)) -> r
                            (Right False) -> none

So you wrap up your (Bool, result) type using Left, and your Bool type
using Right.

Regards,
Chris.




> Thanks
> HP
> _______________________________________________
> Glasgow-haskell-users mailing list
> Glasgow-haskell-users at haskell.org
> http://www.haskell.org/mailman/listinfo/glasgow-haskell-users
>


More information about the Glasgow-haskell-users mailing list