Search code examples
f#functional-programmingdiscriminated-union

F# - Can I return a discriminated union from a function


I have the following types:

type GoodResource = {
    Id:int;
    Field1:string }


type ErrorResource = {
    StatusCode:int;
    Description:string }

I have the following discriminated union:

type ProcessingResult = 
    | Good of GoodResource
    | Error of ErrorResource

Then want to have a function that will have a return type of the discriminated union ProcessingResult:

let SampleProcessingFunction value =
    match value with
    | "GoodScenario" -> { Id = 123; Field1 = "field1data" }
    | _ -> { StatusCode = 456; Description = "desc" }

Is what I am trying to do possible. The compiler is giving out stating that it expects GoodResource to be the return type. What am I missing or am I completely going about this the wrong way?


Solution

  • As it stands, SampleProcessingFunction returns two different types for each branch.

    To return the same type, you need to create a DU (which you did) but also specify the case of the DU explicitly, like this:

    let SampleProcessingFunction value =
        match value with
        | "GoodScenario" -> Good { Id = 123; Field1 = "field1data" }
        | _ -> Error { StatusCode = 456; Description = "desc" }
    

    You might ask "why can't the compiler figure out the correct case automatically", but what happens if your DU has two cases of the same type? For example:

    type GoodOrError = 
        | Good of string
        | Error of string
    

    In the example below, the compiler cannot determine which case you mean:

    let ReturnGoodOrError value =
        match value with
        | "GoodScenario" -> "Goodness"
        | _ -> "Badness"
    

    So again you need to use the constructor for the case you want:

    let ReturnGoodOrError value =
        match value with
        | "GoodScenario" -> Good "Goodness"
        | _ -> Error "Badness"