Haskell inheritance, data, constructors

  • A+
Category:Languages

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

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 some overlapping properties (velocity, position). That also meant that I had to give them different names per data class ("oneVelocity", "twoVelocity", ...).

Is there a way I can let these types of data extend something? I thought of using one datatype with multiple constructors, but some of these current data classes are very different and I don't thing they should reside in one data class with multiple constructors.

 


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 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: