【问题标题】:Compiler not recognizing defined type编译器无法识别定义的类型
【发布时间】:2023-03-11 06:50:01
【问题描述】:

由于某种原因,F# 无法识别我定义的类型。我有几种类型:

type point = int * int
type colour = int * int * int

type figure =
  | Circle of point * int * colour
  | Rectangle of point * point * colour
  | Mix of figure * figure

pointcolour 类型工作正常,但是当我尝试编译如下函数时:

let testFig : figure =
    (50,50), 45, (255,0,0)

编译器抛出一个fs001 异常,并说它预期figure 但得到(int*int) * int * (int*int*int)(这是图中的一部分!)。

我有点迷茫,不明白为什么它不起作用。

【问题讨论】:

  • 您希望它如何工作?例如,您如何区分创建CircleRectangle
  • 该类型将用于函数中,该函数使用模式加工,因此区别应该只是将其定义为let testCircle = (50,50), 45, (255,0,0)let testRect = (0,0), (50,50) (255,0,0),例如。那么模式匹配就可以得到所有的参数
  • 哦,对不起,我误认为它们具有相同的有效负载类型,因为我猜它们都以 int 结尾。无论如何,我的观点是它们可以具有相同类型的有效载荷,如果它们有,你必须以其他方式区分它们。这就是名称的用途。否则,这可以通过阅读the language reference 轻松回答。当您对基本语言概念有疑问时,养成参考它的习惯并不是一个坏主意。

标签: f#


【解决方案1】:

要创建figure 值,您需要指定要创建的案例的名称。例如,如果你想创建Circle,你需要写:

let testFig : figure =
    Circle((50,50), 45, (255,0,0))

如果没有Circle 构造函数,您只需创建一个值(50,50), 45, (255,0,0),它的类型为(int * int) * int * (int * int * int)。这与point * int * color 相同(因为pointcolor 只是别名)。

【讨论】:

    猜你喜欢
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 2020-11-13
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    相关资源
    最近更新 更多