繁体   English   中英

Haskell继承,数据,构造函数

[英]Haskell inheritance, data, constructors

所以我想为我的Asteroids游戏/作业定义多个数据类:

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”,......)。

有没有办法让这些类型的数据扩展? 我想过使用一个带有多个构造函数的数据类型,但是这些当前数据类中的一些是非常不同的,我不应该将它们存放在一个具有多个构造函数的数据类中。

您应该只为所有这些使用单一数据类型,但参数化具体细节:

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

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的答案 ,这是处理这种方法的一种更好的方法。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM