[Haskell-cafe] A simple beginner question

Ronald Guida oddron at gmail.com
Tue Jun 3 20:48:39 EDT 2008


Adam Smyczek wrote:
> 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?

Here's one way to do it:

filter (\x -> case x of A -> True; otherwise -> False) sampleTypes
  ==> [A]

filter (\x -> case x of B _ -> True; otherwise -> False) sampleTypes
  ==> [B 5]

filter (\x -> case x of C _ -> True; otherwise -> False) sampleTypes
  ==> [C "test"]

Your idea works just as well:
> isA :: SampleType -> Bool
> isA A = True
> isA _ = False

filter isA sampleTypes
  ==> [A]

There is a third possibility:  Have you learned about the maybe
function or the either function yet?
  maybe :: b -> (a -> b) -> Maybe a -> b
  either :: (a -> c) -> (b -> c) -> Either a b -> c

I would call these "mediating morphisms", where "morphism" is techno-
babble for "function". You could write your own version of one of these
for SampleType.  Assuming you have:

  data SampleType = A | B Int | C String

You could write:

  sampletype :: t
            -> (Int -> t)
            -> (String -> t)
            -> SampleType -> t
  sampletype a bf cf s =
     case s of
       A -> a
       B n -> bf n
       C s -> cf s

  isA = sampletype True (const False) (const False)
  isB = sampletype False (const True) (const False)
  isC = sampletype False (const False) (const True)

filter isA sampleTypes
  ==> [A]

This (the mediating morphism) is probably overkill for what you want
to do, though.


More information about the Haskell-Cafe mailing list