我正在构建一个类型系统,并且有一个可以支持所有其他类型的变体类型。下面是一个简单的示例,其中允许使用 int32
、float
和 str
:
`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://learn.microsoft.com/en-us/powerquery-m/m-spec-types .
最佳答案
存在许多不同类型系统是有原因的。
恐怕没有正确的方法,如果不深入了解您的需求和限制,就无法回答您的问题。
一般答案是:“您的类型越具体 - 越好(*)”。
如果你可以在你的类型系统中表达,例如,一组长度为素数的电子邮件 - 那么你的类型系统将在更多情况下有用,与不能表达这种类型的系统相比......
(*) 但它会带来成本:
- 这样的类型系统使用起来可能是一场噩梦。
- 实现这样的类型系统可能是一场噩梦。
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
关于types - Variant 与 ListVariant 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68979567/