【问题标题】:How does one resolve F# Type Reference Errors?如何解决 F# 类型引用错误?
【发布时间】:2009-05-11 15:14:40
【问题描述】:

我翻阅了我的书,并在谷歌上搜索了所有搜索词,但我仍然找不到这个问题的示例或答案:

以下代码无法编译,因为在声明 Entity 时尚未声明类型 Effect 和类型 Affect。所以我不明白如何解决这个问题。

在 C++ 中,这个问题是通过在 h 文件中声明原型然后包含 h 文件来解决的。在 C# 中,这从来都不是问题。那么在 F# 中是如何解决的呢?

#light
type Entity = 
    { 
        Name:string; 
        Affects:List<Affect>; //Compile error: The type Affect is not defined
        Effects:List<Effect>; //Compile error: the type Effect is not defined
    }

type Effect = 
    { 
        Name:string; 
        //A function pointer for a method that takes an Entity and returns an Entity
        ApplyEffect:Entity -> Entity;
    }

type Affect = 
    { 
        Name:string; 
        //A List of Effects that are applied by this Affect Object
        EffectList:List<Effect>; 
        //A function pointer to return an Entity modified by the listed Effects
        ApplyAffect:Entity->Entity;
    }

这里的基本目标是实体类型的对象应该能够列出它可以应用于实体类型的对象的影响。实体还可以列出已应用到它的效果。这样,通过将所有效果与原始实体状态折叠起来,就可以找到实体的“当前”状态。

感谢您的宝贵时间,

--亚当·伦达

【问题讨论】:

标签: f# mutual-recursion


【解决方案1】:

我相信这是正确的答案:

http://langexplr.blogspot.com/2008/02/defining-mutually-recursive-classes-in.html

所以...

type Entity = 
    { 
        Name:string; 
        Affects:List<Affect>; 
        Effects:List<Effect>; 
    }
and Effect = 
    { 
        Name:string; 
        ApplyEffect:Entity -> Entity;
    }
and  Affect = 
    { 
        Name:string; 
        EffectList:List<Effect>; 
        ApplyAffect:Entity->Entity;
    }

【讨论】:

  • 是的 - 这正是我要发布的内容,现在我找到了。第 8 章“真实世界的函数式编程”:)
  • 第 3 章,“专家 f#”第 67 页
  • Hrmm...我正要发布同样的内容,但在收到编译器错误后得出结论,这是不可能的!原来我只是语法有点错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
  • 1970-01-01
  • 2019-11-11
  • 2013-06-28
  • 1970-01-01
  • 1970-01-01
  • 2017-05-01
相关资源
最近更新 更多