所以我有Gitem型
type Gitem =
|Weapon of Weapon
|Bomb of Bomb
|Monster of Monster
|Armour of Armour
|Potion of Potion
|None
Run Code Online (Sandbox Code Playgroud)
这用于在记录中存储不同类型的对象,要清楚,我遇到问题的类型如下所示:
type Monster={
name:string;
dVal:float;
dType:DamType;
hVal:float;
info:string;
dInfo:string;
dCry:string;
Special:bool;
sItem:obj;
}
type Armour={
name:string;
aVal:float;
dType:DamType;
info:string;
iSpace:int;
hidden:bool;
}
type Weapon={
name:string;
dVal:float;
dType:DamType;
info:string;
iSpace:int;
hidden:bool;
}
Run Code Online (Sandbox Code Playgroud)
问题是,Gitem将Monster作为一种潜在类型,但是怪物可以拥有炸弹,武器或盔甲作为他们的系统,因此我制造了类型物体.后来在我的代码中写道:
match monster.sItem with //gives them the item if the monster drops one
| Bomb bomb ->
procBomb bomb
| Weapon weap ->
procWeap weap
| Potion pot ->
procPot pot
| Armour arm ->
procArm arm
Run Code Online (Sandbox Code Playgroud)
我得到的错误是表达式应该是Gitem,而不是obj,但是我不能将怪物sitem字段作为Gitem,因为Gitem使用怪物作为可能类型而不允许.我尝试制作另一种像Gitem这样的类型除了怪物之外的所有类型,但这也会导致问题.我是大学的第二年,任何帮助将不胜感激
可以使用and关键字声明相互递归类型:
type A = { b : B }
and B = { a : A option }
Run Code Online (Sandbox Code Playgroud)
此外,F#4.1引入了递归模块(和命名空间),它们允许模块(命名空间)级别的相互递归类型.如果您有许多冗长的相互依赖类型(注意没有and),这很有用:
module rec RecursiveModule =
type A = { b : B }
type B = { a : A option }
Run Code Online (Sandbox Code Playgroud)