-2
如何指定與另一種類型共享類型定義的類型?如何指定與另一種類型共享類型定義的類型?
下面的代碼無法編譯:
[<Test>]
let ``move checker``() =
{ Position={ X=1; Y=1 } } |> moveBlack NorthEast
|> should equal { Position={ X=2; Y=2 } }
這是因爲我傳遞到moveBlack功能記錄被映射到RedChecker而不是BlackChecker。
類型不匹配。期待 RedChecker - >「一個,但給定一個 BlackChecker - > 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 } }
的可能的複製[F#記錄:字段名稱相同( http://stackoverflow.com/questions/5231355/f-records-fields-with-identical-names) – ildjarn
我認爲你甚至會尋找類似這樣的事實可能會指出你的類型定義存在問題。爲什麼'BlackChecker'和'RedChecker'而不是'Checker'和另外一個'Color'字段?除了顏色之外,它們在功能上是相同的,不是嗎? – TeaDrivenDev