Haskell inheritance, data, constructors

前端 未结 2 858
星月不相逢
星月不相逢 2021-01-19 10:22

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

data One = One {oneVelocity :: Velocity, onePosition :: Position, (((other proper         


        
2条回答
  •  北恋
    北恋 (楼主)
    2021-01-19 10:56

    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
    

提交回复
热议问题