使用3种不同的基本类型创建区别联合类型的列表

问题描述 投票:2回答:2

所以我试图创建一个歧视联合类型的列表,如;

type ColType = Int of int | Float of float | String of string 

然后插入到列表中,例如

let addToList (list : ColType list) (col : ColType) =
let list' = list @[col]
list'

但是我不确定如何初始化coltype值,因为我只获取int - > coltype等值。

我试过这个功能

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

这显然不起作用,因为它将返回不同的值,所以你将如何解决这个问题?

types syntax f# discriminated-union
2个回答
1
投票

使用match检查多个选项和:?以匹配类型:

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"

0
投票
type Food = Hamburgers of int | Soda of float | Other of string 
module Food = 
    let tryCreate food = 
        match box food with
        | :? int as i -> Some(Hamburgers i)
        | :? float as f -> Some(Soda f)
        | :? string as s -> Some(Other s)
        | _ -> None

let burgers = Hamburgers 7
let soda = Soda 3.2
let mozzarellaSticks = Other "Mozzarella Sticks"
let mysteryMeat = Option.toList(Food.tryCreate "nobody knows")

let list = [burgers; soda; mozzarellaSticks] @ mysteryMeat

通过使用Option作为我的tryCreate的返回类型,我不会得到任何运行时异常。您还会注意到我已经尝试创建与我的业务目标相关联的DU标签。这使得表达意图更容易,并使联合比简单的整数,字符串和浮点数更有用。大多数时候我知道我的类型,因为类型对应于业务用途,所以我不必编写或使用tryCreate。通常在实践中,将基元映射到我们有区别的联盟并不是很有意义,例如,如果我们添加了一个| Hotdogs of int,如果我们添加的任何int是热狗或汉堡包,则它是不明确的。

© www.soinside.com 2019 - 2024. All rights reserved.