如何复制受歧视的工会案例值?
以下代码有一些重复:
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 })
你要求的东西不能在没有反射技巧的F#中完成.
这里有一个常识性的解释:联合案例在其下面具有完全相同的数据是非常罕见的.在这种情况下,它可能表明联合案例本身只是用于标记数据的"标签",因此应该与数据"并排"编码,而不是"围绕"它.由于这种联合类型是罕见的例外,因此发明语言机制来支持它们是没有意义的.
这种合理化很好地适用于您的特定情况:检查器的颜色是"标签",应该"位于"位置,而不是"包裹"它.如果将检查器定义为{ pos: Position; color: Color },则可以在不触及颜色的情况下更新位置.
| 归档时间: | 
 | 
| 查看次数: | 101 次 | 
| 最近记录: |