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

前提是你 提交于 2019-12-05 01:56:28

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"

You have to state the case of the union type you want to return in either branch.

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

I suggest to read this excellent articles by Scott Wlaschin Railway Oriented Programming

{ Id = 123; Field1 = "field1data" } is a value of type GoodResource, not of type ProcessingResult. To create a value of type ProcessingResult, you need to use one of its two constructors: Good or Error.

So your function can be written like this:

let SampleProcessingFunction value =
    match value with
    | "GoodScenario" -> Good { Id = 123; Field1 = "field1data" }
    | _ -> Error { StatusCode = 456; Description = "desc" }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!