So I want to define multiple data classes for my Asteroids game/assignment:
data One = One {oneVelocity :: Velocity, onePosition :: Position, (((other proper
There is no inheritance in Haskell (at least, not the kind you associate with object-oriented classes). You just want composition of data types.
data Particle = Particle { velocity :: Velocity
, position :: Position
}
-- Exercise for the reader: research the GHC extension that
-- allows all three of these types to use the same name `p`
-- for the particle field.
data One = One { p1 :: Particle
, ... }
data Two = Two { p2 :: Particle
, ... }
data Three = Three { p3 :: Particle
, ... }
Or, you can define a type that encapsulates the other properties, and let those be added to different kinds of Particle
s.
data Properties = One { ... }
| Two { ... }
| Three { ... }
data Particle = Particle { velocity :: Velocity
, position :: Position
, properties :: Properties
}
(Or see @leftaroundabout's answer, which is a nicer way of handling this approach.)
You should probably use just a single data type for all of these, but parameterised on the specific details:
data MovingObj s = MovingObj
{ velocity :: Velocity
, position :: Position
, specifics :: s }
Then you can create e.g. asteroid :: MovingObj AsteroidSpecifics
, but you can also write functions that work with any such moving object like
advance :: TimeStep -> MovingObj s -> MovingObj s
advance h (MovingObj v p s) = MovingObj v (p .+^ h*^v) s