Haskell inheritance, data, constructor

So I want to define multiple data classes for my Asteroids game/job:

data One = One {oneVelocity :: Velocity, onePosition :: Position, (((other properties unique to One))))
data Two = Two {twoVelocity :: Velocity, twoPosition :: Position, (((other properties unique to Two)) ))
data Three = Three {threeVelocity :: Velocity, threePosition :: Position, (((other properties unique to Three))))

As you can see, I have multiple Data types with overlapping attributes (velocity, position). This also means that I have to give each data type a different name (“oneVelocity”, “twoVelocity”,…).

Is there a way to make These types of data extensions? I thought about using a data type with multiple constructors, but some of these current data classes are very different, and I shouldn’t store them in a data class with multiple constructors.

You should only use a single data type for all of them, but parameterize 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 apply to any such moving objects

advance :: TimeStep -> MovingObj s -> MovingObj s
advance h (MovingObj vps) = MovingObj v (p .+^ h*^v) s

So I want to play/homework for my Asteroids Define multiple data classes:

data One = One {oneVelocity :: Velocity, onePosition :: Position, (((other properties unique to One)))} 
data Two = Two {twoVelocity :: Velocity, twoPosition :: Position, (((other properties unique to Two))))
data Three = Three {threeVelocity :: Velocity, threePosition :: Position, (((other properties unique to Three))))

As you can see, I have multiple data classes with overlapping properties (speed, position). This also means that I have to Classes are given different names (“oneVelo city”,”twoVelocity”,……).

Is there a way to expand these types of data? I thought about using a data type with multiple constructors, but some of these current data classes are very different, and I shouldn’t store them in a data class with multiple constructors.

You should only use a single data type for all of these, but the specific details of parameterization:

data MovingObj s = MovingObj
{velocity :: Velocity
, position :: Position
, specifics :: s }

Then you can create for example asteroid :: MovingObj AsteroidSpecifics, but You can also write functions suitable for any such moving objects

advance :: TimeStep -> MovingObj s -> MovingObj s
advance h (MovingObj vps) = MovingObj v (p .+^ h*^v) s

Leave a Comment

Your email address will not be published.