F#如何通过match语句确定值的类型? [英] F# How to have a value's type determined by a match statement?

查看:85
本文介绍了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语句确定值的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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