如何複製區分的工會案例值?如何複製區分的工會案例值?
下面的代碼有一些重複:
let move (direction:Direction) (checker:Checker) =
match checker with
| Red xy -> Red { xy with X=2; Y=2 }
| Black xy -> Black { xy with X=2; Y=2 }
具體來說,我不希望指定檢查的類型,只是設置其記錄值。因此,我不在乎檢查器是紅色還是黑色。我想複製檢查案例值並更新其位置。
我寧願做這樣的事情:
let move (direction:Direction) (checker:Checker) =
match checker with
| _ xy -> _ { xy with X=2; Y=2 }
這裏是我的測試:
[<Test>]
let ``move checker``() =
Black { X=1; Y=1 } |> move NorthEast
|> should equal (Black { X=2; Y=2 })
附錄:
module Test3
open NUnit.Framework
open FsUnit
type Position = { X:int; Y:int }
type Checker = | Red of Position | Black of Position
type Direction =
| NorthEast
| NorthWest
| SouthEast
| SouthWest
(* Functions *)
let move (direction:Direction) (checker:Checker) =
match checker with
| Red xy -> Red { xy with X=2; Y=2 }
| Black xy -> Black { xy with X=2; Y=2 }
[<Test>]
let ``move checker``() =
Black { X=1; Y=1 } |> move NorthEast
|> should equal (Black { X=2; Y=2 })
你的數據類型在裏面。如果這是你的用例,你應該將檢查器定義爲'{pos:Position;顏色:顏色}',那麼你可以在不觸摸顏色的情況下更新位置。 –
啊......這很有道理。順便說一下,無論我的設計問題是否可以複製工會案例值? –