【问题标题】:F# pattern matching on discriminated union containing records包含记录的可区分联合上的 F# 模式匹配
【发布时间】:2019-01-10 14:14:44
【问题描述】:

我正在尝试创建一个简单的场景;受歧视的工会有成员记录。尝试在简单函数中进行模式匹配时出现错误“未定义模式鉴别器”。

type Circle =
  {
  radius : float
  }

type Rectangle =
  {
  width : float
  height : float
  }

type Shape =
  | ACircle of Circle
  | ARectangle of Rectangle


let calcualteArea shape =
   match shape with 
   | Circle(radius) -> System.Math.PI*radius*radius  // error: pattern discriminator not defined
   | Rectangle(width, height) -> width*height

请帮我解决错误。 谢谢

【问题讨论】:

    标签: f# pattern-matching record discriminated-union


    【解决方案1】:

    语法在两个方面与您期望的不同。首先,您应该匹配ACircleARectangle,因为它们是您的Shape 类型案例的名称。可区分的联合案例名称与类型名称不同。其次,模式匹配记录的语法如下:*

    type Rectangle =
        { width: int
          height: int }
    
    let area rectangle =
        match rectangle with
        | { width = width; height = height } -> width * height
    

    鉴于此,您的函数应如下所示:

    let calculateArea shape =
        match shape with 
        | ACircle({ radius = radius }) -> System.Math.PI*radius*radius  // error: pattern discriminator not defined
        | ARectangle({ width = width; height = height }) -> width*height
    

    * 注意这里的模式匹配是严格可选的;您可以同样轻松地使用| ARectangle(rectangle) -> rectangle.width * rectangle.height 来访问这些字段。

    【讨论】:

      猜你喜欢
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 2013-10-19
      • 2019-06-06
      • 2015-03-21
      • 2012-08-27
      • 2018-11-24
      相关资源
      最近更新 更多