Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching polymorphic data in Haskell

Tags:

haskell

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!

like image 259
José Ricardo Ribeiro Avatar asked Nov 30 '22 18:11

José Ricardo Ribeiro


1 Answers

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 Strings or even more Stuffs 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.

like image 115
bheklilr Avatar answered Dec 04 '22 03:12

bheklilr