首页 > 解决方案 > 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 个”。我知道它需要字符串值,但我需要在这里匹配类型。谢谢!

标签: .nettypesf#

解决方案


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


推荐阅读