-2

How do I specify a type that shares a type definition with another type?

The following code does not compile:

[<Test>]
let ``move checker``() =
    { Position={ X=1; Y=1 } } |> moveBlack NorthEast 
                              |> should equal { Position={ X=2; Y=2 } }

This is because the record that I'm passing into the moveBlack function is mapped to RedChecker instead of BlackChecker.

Type mismatch. Expecting a RedChecker -> 'a but given a BlackChecker -> BlackChecker The type 'RedChecker' does not match the type 'BlackChecker'

More than likely, this error occurs because the last type to have this definition is RedChecker:

type BlackChecker = { Position:Position }
type RedChecker =   { Position:Position }

I thought I could specify the black checker by doing this:

(BlackChecker:{ Position={ X=1; Y=1 } })

And thus have:

[<Test>]
let ``move checker``() =
    (BlackChecker:{ { Position={ X=1; Y=1 } }) |> moveBlack NorthEast 
                              |> should equal (BlackChecker:{ { Position={ X=2; Y=2 } })

However, the above code also doesn't compile.

Here's the rest of my code:

(* 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 } }
Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118
  • 1
    Possible duplicate of [F# Records: Fields With Identical Names](http://stackoverflow.com/questions/5231355/f-records-fields-with-identical-names) – ildjarn Jul 25 '16 at 16:50
  • I think the fact that you even look for something like this may point to a problem with your type definitions. Why have `BlackChecker` and `RedChecker` instead of `Checker` with an additional `Color` field? Other than the color, they're functionally identical, aren't they? – TeaDrivenDev Jul 27 '16 at 20:32

1 Answers1

3

The labels of the most recently declared type take precedence over those of the previously declared type. You should be able to do it like this:

({ BlackChecker.Position={ X=1; Y=1 } })
Wesley Wiser
  • 9,491
  • 4
  • 50
  • 69