[Haskell-cafe] A simple beginner question
westondan at imageworks.com
Tue Jun 3 21:09:39 EDT 2008
There's always one more way to do things in Haskell! :)
Here's yet another way to get at the payloads in a list. You don't have
to know how this works to use it:
data SampleType = A | B Int | C String
unA :: SampleType -> [()]
unA A = return ()
unA _ = fail "Not an A"
unB :: SampleType -> [Int]
unB (B b) = return b
unB _ = fail "Not a B"
unC :: SampleType -> [String]
unC (C c) = return c
unC _ = fail "Not a C"
-- I can check for more than one constructor...
-- Note that a single type must be returned,
-- so for C I return e.g. the length of the string
unBorC :: SampleType -> [Int]
unBorC (B b) = return b
unBorC (C c) = return (length c)
unBorC _ = fail "Not a B or C"
For lists, the >>= operator knows to ignore failure and collect anything
else into a new list. The technobabble for this is that  is a Monad.
*Main> let sampleTypes = [A, B 5, C "test", A, A, B 7, C "go"]
*Main> sampleTypes >>= unA
*Main> sampleTypes >>= unB
*Main> sampleTypes >>= unC
*Main> sampleTypes >>= unBorC
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?
> 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.
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
More information about the Haskell-Cafe