我有什么办法可以完全限定受歧视的工会路径吗?

Is there any way for me to fully qualify a discriminated union path?

我有什么方法可以完全限定受歧视的联合路径吗?

我目前有这个:

type PostionOfScott =
    | ScottOnFirst
    | ScottOnSecond
    | ScottOnThird

type PostionOfBrian =
    | BrianOnFirst
    | BrianOnSecond
    | BrianOnThird

type PostionOfCherice =
    | ChericeOnFirst
    | ChericeOnSecond
    | ChericeOnThird

我想这样做:

type PostionOfScott =
    | First
    | Second
    | Third

type PostionOfBrian =
    | First
    | Second
    | Third

type PostionOfCherice =
    | First
    | Second
    | Third

但是,当我提供以下代码时:

(*Functions*)
let hit play batterUp =

    match batterUp with
    | ScottAtBat   -> match play with
                      | Single  -> Scott First
                      | Double  -> Scott Second
                      | Tripple -> Scott Third

我收到以下错误:

Error This expression was expected to have type PostionOfScott but here has type PostionOfCherice

我知道如果有任何歧义,将引用最后声明的可区分联合类型。

但是,有什么方法可以让我完全限定受歧视的工会路径吗? 因此,我想减少工会案例中的冗长。

我认为为每个玩家重复位置类型定义可能不是最佳设计选择。将这些东西分开会更有意义,然后您的问题就会自然消失。

type Position =
    | First
    | Second
    | Third

type Player =
    | Scott
    | Brian
    | Cherice

type PlayerPosition = {Player : Player; Position : Position}

然后你可以进行模式匹配:

let hit play batterUp =
    match batterUp with
    |{Player = Scott; Position = First} -> ...

听起来您正在寻找 RequireQualifiedAccess 属性。

[<RequireQualifiedAccess>]
type PositionOfScott =
    | First
    | Second
    | Third

因此,您需要在 PositionOfScott 成员之外使用 PositionOfScott.First 而不是 First。对于具有通常难以描述的值(如 YesAny)的联合非常有用。