Variant 与 ListVariant 类型

Variant vs ListVariant types

我正在构建一个类型系统,并且有一个可以支持所有其他类型的变体类型。这是一个允许 int32floatstr 的简单示例:

`variant_scalar`
"hello"
NULL
2
2.7

此外,支持可变长度的类型化数组,例如:

`int32_arrar`
[1,2]
[1,2,3]
[1]

现在我有一个关于以下两个变体列的问题,一个仅包含变体数组项,另一个包含标量和数组性质的类型:

`variant_array`
[1,2,"hello"]
["new", [1,2]]
NULL

-------------------------------------

`variant_anything`
1
"hello"
NULL
[1,2,"hello"]

在类型系统(例如,数据库)中处理此问题的正确方法是什么?应该只有一个 Variant 类型支持所有内容,还是应该有一个 VariantArray 类型支持任何数组...但它必须是数组?

我想一个可能有用的参考是 M 语言使用的类型系统:https://docs.microsoft.com/en-us/powerquery-m/m-spec-types

许多不同的类型系统是有原因的。

恐怕没有正确的方法,如果不深入了解您的需求和限制,就无法回答您的问题。

一般答案是:“您的类型越具体 - 越好 (*)”。

如果您可以在您的类型系统中表达,例如,一组长度为质数的电子邮件 - 与无法表达此类类型的系统相比,您的类型系统将在更多情况下有用。 ..

(*) 但这是有代价的:

  1. 这种类型的系统使用起来简直是一场噩梦。
  2. 这样的类型系统实施起来可能是一场噩梦。

Wikipedia 可能不是绝对真理,但很好地概括了主题:

When a programming language evolves a more elaborate type system, it gains a more finely grained rule set than basic type checking, but this comes at a price when the type inferences (and other properties) become undecidable, and when more attention must be paid by the programmer to annotate code or to consider computer-related operations and functioning. It is challenging to find a sufficiently expressive type system that satisfies all programming practices in a type safe manner.

我建议考虑“进化”部分。不要试图建立一个理想。构建 MVP,但要采用一种可以让您在以后从实践中找到 正确方法 时对其进行改进的方式。

但在您的特定示例中,我猜想无论如何您都想实施 Array<T>...而且,实际上,您说您确实如此

Additionally, a typed array of variant length is supported

所以Array<Variant>应该不是问题。没有理由将 T 视为 any but not Variant