0

I want to return a discriminated union type from a function - it conflicts with type inference - how should I change my code so that getKeyA returning KeyA gets changed into 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
weismat
  • 6,743
  • 3
  • 38
  • 55

1 Answers1

4

To make this short: I don't know the definitions of most parts you gave but to return something of type Key you have to use KeyA or KeyB in your example here.

Try this:

type Key = KeyA of KeyA | KeyB of KeyB

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

or maybe this looks better for you

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

You might notice that you only wrap a string or an int into a record - if it's really only one type/value or if you can live with tuples I would strip the additional record:

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
Carsten
  • 49,407
  • 9
  • 85
  • 111