因此,我想为我的小行星游戏/任务定义多个数据类:
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)))}如您所见,我有多个数据类,具有一些重叠的属性(速度、位置)。这也意味着我必须为每个数据类指定不同的名称("oneVelocity“、"twoVelocity”、.)。
有办法让这些类型的数据扩展吗?--我想用一种数据类型和多个构造函数一起使用,但是这些当前的数据类中有一些是非常不同的,我不认为它们应该驻留在一个具有多个构造函数的数据类中。
发布于 2018-10-19 16:36:46
对于所有这些,您可能应该只使用一种数据类型,但是应该在具体细节上进行参数化:
data MovingObj s = MovingObj
{ velocity :: Velocity
, position :: Position
, specifics :: s }然后您可以创建例如asteroid :: MovingObj AsteroidSpecifics,但也可以编写与任何这样的移动对象一起工作的函数,比如
advance :: TimeStep -> MovingObj s -> MovingObj s
advance h (MovingObj v p s) = MovingObj v (p .+^ h*^v) s发布于 2018-10-19 16:08:50
在Haskell中没有继承(至少不是与面向对象类相关联的继承)。您只需要数据类型的组合。
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
, ... }或者,您可以定义封装其他属性的类型,并允许将这些属性添加到不同类型的Particle中。
data Properties = One { ... }
| Two { ... }
| Three { ... }
data Particle = Particle { velocity :: Velocity
, position :: Position
, properties :: Properties
} (或者请参阅@leftaroundabout's answer,这是处理此方法的更好方法。)
https://stackoverflow.com/questions/52896071
复制相似问题