这是我的问题:
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语句确定值的类型?
发布评论