创建具有3种不同原始类型的区分联合类型的列表 [英] Create a list of a discriminate union type with 3 different primitive types
本文介绍了创建具有3种不同原始类型的区分联合类型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我尝试创建具有区别的联合类型的列表,例如;
So I am attempting to create a list of a discriminate union type such as;
type ColType = Int of int | Float of float | String of string
然后插入到列表中,例如
And then insert into a list, such as
let addToList (list : ColType list) (col : ColType) =
let list' = list @[col]
list'
但是我不确定如何初始化coltype值,因为我只能获取int-> coltype等值.
However I am unsure how to initialize the coltype values as I only get values such as int -> coltype etc.
我尝试了此功能
let createColType x =
if x.GetType() = int then
Int x
else if x.GetType() = float then
Float x
else if x.GetType() = string then
String x
else
String x
显然哪个都不行,因为它将返回不同的值,那么您将如何解决呢?
Which obviously doesnt work as it will return different values, so how would you go about solving this?
推荐答案
使用match
检查多个选项,并使用:?
匹配类型:
Use match
to check multiple options and :?
to match the type:
let createColType x =
match box x with
| :? int as i -> ColType.I i
| :? float as f -> ColType.F f
| :? string as s -> ColType.S s
|_-> failwithf "Type not supported %A" <| x.GetType().FullName
createColType 1 |> printfn "%A" // shows: I 1
createColType 2. |> printfn "%A" // shows: F 2.0
createColType "3" |> printfn "%A" // shows: S "3"
这篇关于创建具有3种不同原始类型的区分联合类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文