F#如何通过match语句确定值的类型?

编程入门 行业动态 更新时间:2024-10-25 00:35:51
本文介绍了F#如何通过match语句确定值的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我的问题:

let foo = match bar with | barConfig1 -> configType1(devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex) | barConfig2 -> configType2(devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex) | barConfig3 -> configType3(devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex) | barConfig4 -> configType4(devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex)

我想让foo的类型由match语句确定,但是它总是将foo设置为第一种类型.

I'd like to have the type of foo be determined by the match statement, but it always sets foo to the first type.

type bar = |barConfig1 |barConfig2 |barConfig3 |barConfig4

推荐答案

在F#中,没有语句,只有表达式,并且每个表达式必须具有单个具体类型. match块也是一个表达式,这意味着它必须具有单个具体类型.因此,匹配的每种情况也必须具有相同的类型.

In F#, there are no statements, only expressions, and each expression has to have a single concrete type. A match block is an expression as well, meaning that it has to have a single concrete type. What follows from that is that each case of the match has to have the same type as well.

也就是说,像这样的东西是无效的F#:

That is, something like this is not valid F#:

let foo = // int? string? match bar with // int? string? | Int -> 3 // int | String -> "Three" // string

在这种情况下,类型推断机制将期望匹配的类型与第一种情况的类型相同-int,并且在第二种情况下看到字符串时最终会感到困惑.在您的示例中,发生了同样的事情-类型推断期望所有情况都返回configType1.

In this case, the type inference mechanism will expect the type of the match to be the same as the type of the first case - int, and end up confused when it sees the string in the second. In your example the same thing happens - type inference expects all the cases to return a configType1.

一种解决方法是将值转换为普通的超类型或接口类型.因此,对于您的情况,假设configTypes实现一个公共的IConfigType接口:

A way around it would be by casting the values into a common supertype or interface type. So for your case, assuming the configTypes implement a common IConfigType interface:

let foo = // IConfigType let arg = (devices:DeviceEntities,DeviceStartIndex,inputStartIndex,outputStartIndex) match bar with | barConfig1 -> configType1(arg) :> IConfigType | barConfig2 -> configType2(arg) :> IConfigType | barConfig3 -> configType3(arg) :> IConfigType | barConfig4 -> configType4(arg) :> IConfigType

更多推荐

F#如何通过match语句确定值的类型?

本文发布于:2023-07-30 15:19:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250582.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   类型   match

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!