[英]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.