
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 [5,7] *Main> sampleTypes >>= unC ["test","go"] *Main> sampleTypes >>= unBorC [5,4,7,2] Adam Smyczek wrote:
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.
Thanks, Adam
_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe