[Haskell-cafe] Searching for ADT patterns with elem and find

Ryan Ingram ryani.spam at gmail.com
Wed Nov 12 13:31:36 EST 2008


On Wed, Nov 12, 2008 at 10:20 AM, Derek Elkins <derek.a.elkins at gmail.com> wrote:
> In addition to what others have said, I recommend using functions like
> isTypeB :: T -> Maybe Double
> isTypeB (B d) = Just d
> isTypeB     _ = Nothing
>
> You can recover the Bool version of isTypeB just by post-composing with
> isJust, but this version avoids needing partial functions and often is
> more what you want (i.e. it's a first-class "pattern").  Combining it
> with catMaybes is also a common pattern.

Although if you are using Maybe as a monad, these two pieces of code
are equivalent:

test1 t1 t2 = do
    d1 <- isTypeB t1
    d2 <- isTypeB t2
    return (d1 + d2)

test2 t1 t2 = do
    B d1 <- return t1
    B d2 <- return t2
    return (d1 + d2)

This is because pattern-matching in do-notation implicitly calls
"fail" when the pattern match fails.

  -- ryan


More information about the Haskell-Cafe mailing list