.net - F# 匹配有区别的联合
问题描述
我定义了 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 个”。我知道它需要字符串值,但我需要在这里匹配类型。谢谢!
解决方案
当你定义你的构造函数(例如South of string
)时,你说它们需要一个string
参数。在这些构造函数上进行模式匹配时,您必须使用变量模式来存储给定构造函数的值(或_
忽略它),并且在构造值时也必须提供一个字符串:South s1, Left _ -> East "a string"
. 如果您不需要与构造函数关联的任何类型的值,只需of string
从其定义中删除该部分即可。
推荐阅读
- camunda - 是否可以为外部任务检索消息结束事件中定义的消息?
- javascript - 如何用具有值'X'的数组的索引0处的数据替换变量X
- sql - PostGIS:从 3D 点列表中查找最近的点
- javascript - Javascript 承诺递归返回未定义
- python - 在 Sphinx 中使用 rst_epilog 的动态 URL
- oracle - 自动增量的触发器
- ios - 在 RxSwift 中接收和发送 observable
- python - ax.set_yticklabels 将刻度显示为长小数
- node.js - Returning status code from the node api service
- java - How to transfer all the data from one JFrame to another JFrame through a button?