Haskell inheritance, data, constructors

前端 未结 2 859
星月不相逢
星月不相逢 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:45

    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 Particles.

    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.)

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题