Thursday 29 August 2013

How to model a polymorphic list in Haskell?

How to model a polymorphic list in Haskell?

I'm trying to model some polymorphic-type data in haskell. I understand
why the following code doesn't work, but I'm hoping it illustrates what
I'm trying to do. My question is: what is an idiomatic way to model this
with Haskell? (You don't need to keep the input format the same if there
is a better way - I don't have any existing code or data.)
data Running = Sprint | Jog deriving (Show)
data Lifting = Barbell | Dumbbell deriving (Show)
data Time = Time Integer deriving (Show)
data Pounds = Pounds Integer deriving (Show)
data TimedActivity = TimedActivity Running Time deriving (Show)
data WeightedActivity = WeightedActivity Lifting Pounds deriving (Show)
class Activity a
instance Activity TimedActivity
instance Activity WeightedActivity
-- I have a list of activities
main :: IO ()
main = putStrLn $ show [ TimedActivity Sprint (Time 10)
, WeightedActivity Barbell (Pounds 100)
]
-- I then want to apply functions to generate summaries and
-- reports from those activities, i.e.:
extractLifts :: (Activity x) => [x] -> [WeightedActivity]
extractTimes :: (Activity x) => [x] -> [TimedActivity]

No comments:

Post a Comment