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

Derek Elkins derek.a.elkins at gmail.com
Wed Nov 12 13:20:16 EST 2008


On Wed, 2008-11-12 at 10:09 +0000, Paul Keir wrote:
> Hi All,
> 
> If I have an ADT, say
> 
> data T
>  = A String Integer
>  | B Double
>  | C
>  deriving(Eq)
> 
> and I want to find if a list (ts) of type T contains an element of
> subtype "B Double", must my "containsTypeX" function use a second
> "isTypeX" function as follows:
> 
> isTypeB :: T -> Bool
> isTypeB (B _) = True
> isTypeB _     = False
> 
> containsTypeB :: [T] -> Bool
> containsTypeB ts = maybe False (\x -> True) (find isTypeB ts)
> 
> I understand that while something like "find C ts" will work, "find
> (isTypeB _) ts" will not, but is there no such thing as a pattern
> combinator(?), or lambda that could help with this situation. I find I
> have many individual "isTypeB" functions now.
> 
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.



More information about the Haskell-Cafe mailing list