F# 使用区分联合类型

F# Using Discrimated Union Types

我想 return 从函数中区分联合类型 - 它与类型推断冲突 - 我应该如何更改我的代码以便将 getKeyA returning KeyA 更改为 Key?

      type KeyA = {keyString:string}
type KeyB = {keyInt:int}
type Key = KeyA | KeyB

let getKeyA id =
         {keyString="123"}
let getKeyB id = 
         {keyInt=2}

let getKey (id) :Key = 
     match id with 
      | 1 -> getKeyA id 
      | _ -> getKeyB id

简而言之:我不知道你给出的大多数部分的定义,但对于 return 类型的东西 Key 你必须使用 KeyAKeyB 在您的示例中。

试试这个:

type Key = KeyA of KeyA | KeyB of KeyB

let getKey id : Key = 
    match id with 
    | 1 -> KeyA (getKeyA id)
    | _ -> KeyB (getKeyB id)

或者这看起来更适合你

type KeyA = {keyString:string}
type KeyB = {keyInt:int}
type Key = KeyA of KeyA | KeyB of KeyB

let getKeyA id =
    { keyString="123" }
    |> KeyA

let getKeyB id = 
    { keyInt=2 }
    |> KeyB

let getKey id : Key = 
     match id with 
      | 1 -> getKeyA id 
      | _ -> getKeyB id

您可能会注意到您只将 stringint 包装到一条记录中 - 如果它真的只有一个 type/value 或者如果您可以接受元组,我会去掉附加记录:

type Key = KeyA of string | KeyB of int

let getKeyA id = KeyA "123"

let getKeyB id = KeyB 2

let getKey id : Key = 
     match id with 
      | 1 -> getKeyA id 
      | _ -> getKeyB id