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

wren ng thornton wren at freegeek.org
Wed Nov 12 13:36:12 EST 2008

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)

Many other good posts have obviated the original question, but just to 
answer it directly. You can turn isTypeB into a lambda by using a case 

     isTypeB = \t -> case t of B _ -> True ; _ -> False

And from there you can just inline the definition in order to remove 
isTypeB. Pattern matching in function definitions is just sugar for the 
case expression version, so this transformation is just what the 
compiler would be doing anyways.

Live well,

More information about the Haskell-Cafe mailing list