【问题标题】:F# Match with discriminated unionsF# 匹配有区别的联合
【发布时间】:2018-11-24 02:16:05
【问题描述】:

我定义了 2 个可区分的联合:“Direction”和“TurnCommand”:

type Direction = 
| South of string
| East of string
| North of string
| West of string

type TurnCommand = 
| Left of string
| Right of string

然后我在制作 TurnCommand 后定义函数有新的方向:

type Turn = Direction -> TurnCommand -> Direction

这里没有实现这个功能:

let Do:Turn = fun(startDirection) (turn) -> 
    match startDirection, turn with
    | South, Left  -> East 
    | East,  Left  -> North
    | North, Left  -> West
    | West,  Left  -> South
    | South, Right -> West 
    | East,  Right -> South
    | North, Right -> East
    | West,  Right -> North

有错误:“构造函数应用于 0 个参数,但需要 1 个”。 我知道它需要字符串值,但我需要在这里匹配类型。 谢谢!

【问题讨论】:

    标签: .net types f#


    【解决方案1】:

    当你定义你的构造函数(例如South of string)时,你说它们需要一个string 参数。在这些构造函数上进行模式匹配时,您必须使用变量模式来存储给定构造函数的值(或 _ 忽略它),并且在构造值时也必须提供一个字符串:South s1, Left _ -> East "a string"。如果您不需要与构造函数关联的任何类型的值,只需从其定义中删除 of string 部分。

    【讨论】:

      猜你喜欢
      • 2019-06-29
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 2011-10-23
      • 1970-01-01
      • 2019-01-10
      • 2019-06-06
      • 2015-08-30
      相关资源
      最近更新 更多