如何指定与其他类型共享类型定义的类型?
以下代码无法编译:
[<Test>]
let ``move checker``() =
{ Position={ X=1; Y=1 } } |> moveBlack NorthEast
|> should equal { Position={ X=2; Y=2 } }
这是因为我传入moveBlack函数的记录被映射到RedChecker而不是BlackChecker。
类型不匹配。期待一个 RedChecker - &gt; '但是给了一个 BlackChecker - &gt; BlackChecker“RedChecker”类型与“BlackChecker”类型
不匹配
很可能发生此错误,因为具有此定义的最后一个类型是RedChecker:
type BlackChecker = { Position:Position }
type RedChecker = { Position:Position }
我认为我可以通过这样做来指定黑色检查器:
(BlackChecker:{ Position={ X=1; Y=1 } })
因此有:
[<Test>]
let ``move checker``() =
(BlackChecker:{ { Position={ X=1; Y=1 } }) |> moveBlack NorthEast
|> should equal (BlackChecker:{ { Position={ X=2; Y=2 } })
但是,上面的代码也没有编译。
以下是我的其余代码:
(* Types *)
type Color = | Red | Black
type North = NorthEast | NorthWest
type South = SouthEast | SouthWest
type Position = { X:int; Y:int }
type BlackChecker = { Position:Position }
type RedChecker = { Position:Position }
(* Functions *)
let moveBlack (direction:North) (checker:BlackChecker) =
match direction with
| NorthEast -> { checker with Position= { X=2; Y=2 } }
| NorthWest -> { checker with Position= { X=1; Y=2 } }
(* Tests *)
[<Test>]
let ``move checker``() =
{ Position={ X=1; Y=1 } } |> moveBlack NorthEast
|> should equal { Position={ X=2; Y=2 } }
答案 0 :(得分:3)
({ BlackChecker.Position={ X=1; Y=1 } })