[Haskell-cafe] A simple beginner question

Don Stewart dons at galois.com
Tue Jun 3 23:56:32 EDT 2008


adam.smyczek:
> Example:
> 
> data SampleType = A | B Int | C String | D -- .... etc.
> 
> sampleTypes = [A, B 5, C "test"] :: [SampleType]
> 
> How do I find for example element A in the sampleTypes list?
> Do I have to create e.g.:
> 
> isA :: SampleType -> Bool
> isA A = True
> isA _ = False
> 
> for every constructor and use find?
> It feels like this is not the quicker method.

This is where the implicit filtering in a list comprehension comes in
really handy,

    data T = A | B Int | C String | D
        deriving Show

    xs = [A, B 5, C "test", D]

    main = do print [ A | A       <- xs ] -- filter A's
              print [ x | x@(C _) <- xs ] -- filter C's

    {-

        *Main> main
        [A]
        [C "test"]

    -} 


More information about the Haskell-Cafe mailing list