How do I model inheritance in Haskell?

前端 未结 3 2075
走了就别回头了
走了就别回头了 2021-01-04 19:14

I am attempting to create a game engine that is composed of a few different types:

data Camera = Camera ...
data Light = SpotLight ... | DirectionalLight ...         


        
3条回答
  •  时光取名叫无心
    2021-01-04 20:21

    You'll want to begin to depend on things like typeclasses and object encodings. The first method is to encode the common interface as a typeclass each type inherits from.

    class PhysicalObject o where
      pos      :: o -> Vector3
      velocity :: o -> Vector3
    

    The second is to build a common object

    data PhysicalObject = PhysicalObject { poPos :: Vector3, poVelocity :: Vector3 }
    
    data Monster = Monster { monsterPO :: PhysicalObject
                           , ... monsterStuff ...
                           }
    

    which could even be used to instantiate the first typeclass

    instance PhysicalObject PhysicalObject where
      pos      = poPos
      velocity = poVelocity
    
    instance PhysicalObject Monster where
      pos      = pos      . monsterPO
      velocity = velocity . monsterPO
    

    Be careful with typeclass encodings like this, though, as too great a use of them often causes ambiguity when reading code. It can be difficult to understand the types and know which instance is being used.

提交回复
热议问题