F# - 我可以从一个函数返回一个有区别的联合 [英] F# - Can I return a discriminated union from a function

查看:136
本文介绍了F# - 我可以从一个函数返回一个有区别的联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几种类型:

 类型GoodResource = {
Id:int;
Field1:string}


类型ErrorResource = {
StatusCode:int;
描述:string}

我有以下歧视联合:

 类型ProcessingResult = 
|良好的资源
| ErrorResource的错误

然后想拥有一个函数,该函数将具有辨别联合ProcessingResult的返回类型:

 让SampleProcessingFunction值= 

匹配值| GoodScenario - > {Id = 123; Field1 =field1data}
| _ - > {StatusCode = 456; Description =desc}

是我想要做的事情。编译器发出声明,希望GoodResource成为返回类型。我错过了什么,或者我完全用这种错误的方式去做?

现在, SampleProcessingFunction 为每个分支返回两个不同的类型。



要返回相同的类型,你需要创建一个DU(你所做的),但也明确指定了DU的情况,如下所示:

  let SampleProcessingFunction值= 

|匹配值GoodScenario - >好{Id = 123; Field1 =field1data}
| _ - >错误{StatusCode = 456; Description =desc}

您可能会问为什么编译器不能找出正确的大小写自动,但如果您的DU有两种相同类型的情况会发生什么?例如:

 类型GoodOrError = 
|良好的字符串
|错误的字符串

在下面的例子中,编译器无法确定您的意思:

 让ReturnGoodOrError value = 

匹配值| GoodScenario - > 善良
| _ - > Badness

所以你需要使用你想要的构造函数:

 让ReturnGoodOrError value = 

匹配值| GoodScenario - >良好的善良
| _ - >错误Badness


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?

解决方案

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"

这篇关于F# - 我可以从一个函数返回一个有区别的联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆