Lets say we have a data defined named Stuff:
data Stuff = Stuff1 Int
| Stuff2 Int
| Stuff3 Int
sumStuff :: [Stuff] -> Int
sumStuff [] = 0
sumStuff ((Stuff1 x):xs) = x + sumStuff xs
sumStuff ((Stuff2 x):xs) = x + sumStuff xs
sumStuff ((Stuff3 x):xs) = x + sumStuff xs
sumStuff' :: [Stuff] -> Int
sumStuff' [] = 0
sumStuff' ((_ x):xs) = x+sumStuff xs
How can I match all types without pattern matching like in the wrong definition in sumStuff' ?
Thank you in advance!
You could take a different approach with your data structure if it's as homogenous as your example:
data StuffType = Stuff1 | Stuff2 | Stuff3 deriving (Eq, Show)
data Stuff a = Stuff StuffType a deriving (Eq, Show)
extractStuff :: Stuff a -> a
extractStuff (Stuff _ a) = a
sumStuff :: Stuff Int -> Int
sumStuff = sum . map extractStuff
I've even made the value contained in Stuff
polymorphic, in case you wanted to store String
s or even more Stuff
s in them. This approach allows you to pattern match on the StuffType
when you need it, but stick with a single pattern case when you don't.
You could also define this using records to avoid pattern matches altogether:
data Stuff a = Stuff { stuffType :: StuffType, extractStuff :: a } deriving (Eq, Show)
and sumStuff
would have the same definition, but you wouldn't need to define extractStuff
manually.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments