Haskell继承,数据,构造函数 [英] Haskell inheritance, data, constructors

查看:115
本文介绍了Haskell继承,数据,构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I want to define multiple data classes for my Asteroids game/assignment:

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

As you can see I have multiple data classes with some overlapping properties (velocity, position). That also meant that I had to give them different names per data class ("oneVelocity", "twoVelocity", ...).

有没有办法让这些类型的数据扩展某些内容?我想到了将一个数据类型与多个构造函数一起使用,但是这些当前数据类中的一些非常不同,我不知道它们应该驻留在具有多个构造函数的一个数据类中.

Is there a way I can let these types of data extend something? I thought of using one datatype with multiple constructors, but some of these current data classes are very different and I don't thing they should reside in one data class with multiple constructors.

推荐答案

对于所有这些,您可能应该只使用一种数据类型,但是在具体细节上使用参数化:

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 }

然后您可以创建例如asteroid :: MovingObj AsteroidSpecifics,但是您也可以编写可与任何此类移动对象一起使用的函数,例如

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

这篇关于Haskell继承,数据,构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆