开发者

Does F# have a AND in types or a type hierarchy with parent Number?

开发者 https://www.devze.com 2023-02-16 08:19 出处:网络
I want t开发者_运维技巧o define a list of ints and floats, where [1,2.0] should be a valid construction.

I want t开发者_运维技巧o define a list of ints and floats, where [1,2.0] should be a valid construction.

Does F# have a AND in types or a type hierarchy with int and floats derived from Number for example?

Thanks.


No, F# / .NET does not have a numeric tower like Python, or a common Number base type like Java.

Perhaps you could define a discriminant union like so for your purposes:

type Number =
    | Float of float
    | Int of int

let x = [Float(3.2); Int(2)] //val x : Number list = [Float 3.2; Int 2]


F# does not have a numerical tower like Lisp/Scheme.

The only kind of union type supported is a disjoint union which must include a tag. You could write:

type Num = Int of int | Float of float

[Int 1; Float 2.0]

The value above has type Num list. To consume the elements, you would use pattern matching:

match num with
| Int x -> printf "%i" x
| Float x -> printf "%f" x
0

精彩评论

暂无评论...
验证码 换一张
取 消