💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
合一 是类型系统的心脏,极大的提高Haxe程序的健壮性。它描述了检查是否一个类型和另一个类型兼容的过程。 > Unification is the heart of the type system and contributes immensely to the robustness of Haxe programs. It describes the process of checking if a type is compatible to another type. **合一** >[warning] 定义:合一 两个类型 A 和 B之间的合一是一个定向的处理,如果A可以被分配到B则解决了问题。它可以使任何类型发生改变,如果它是或者有一个 单形(第2.9节)。 >[warning] Definition: Unification Unification between two types A and B is a directional process which answers the question if A can be assigned to B. It may mutate either type if it is or has a monomorph (2.9). 合一错误非常容易被触发: > Unification errors are very easy to trigger: ~~~ class Main { static public function main() { // Int should be String var s:String = 1; } } ~~~ 我们尝试分配一个Int类型的值到一个String类型变量,这会使编译器尝试使用String统一Int。当然,这是不允许的,使编译器发出一个错误 “Int should be String”。 > We try to assign a value of type Int to a variable of type String, which causes the compiler to try and unify Int with String. This is, of course, not allowed and makes the compiler emit the error Int should be String. 在这个特殊情况下,合一被一个赋值操作触发,一个“被分配到”的上下文定义是直观的。这是几种需要执行合一的情况之一: > In this particular case, the unification is triggered by an assignment, a context in which the “is assignable to” definition is intuitive. It is one of several cases where unification is performed: **赋值**:如果 a 被分配为 b,a 的类型通过 b的类型合一。 > **Assignment**: If `a` is assigned to `b`, the type of `a` is unified with the type of `b`. **函数调用**:我们简短的看过这个,当介绍函数类型(第2.6节)的时候。通常,编译器尝试统一第一个个指定的参数类型到第一个期待的参数类型。第二个指定的参数类型到第二个期待的参数类型等等直到所有参数类型被处理。 > **Function call**: We have briefly seen this one while introducing thefunction(2.6)type. In general, the compiler tries to unify the first given argument type with the first expected argument type, the second given argument type with the second expected argument type and so on until all argument types are handled. **函数返回**:当一个函数有一个 return e 表达式,e的类型使用函数的返回类型统一。如果函数没有明确的返回类型,它被推断为e的类型,随后return 表达式针对它进行推断。 > **Function return**: Whenever a function hasa return e expression, thetypeof e is unified with the function return type. If the function has no explicit return type,it is inferred to the type of e and subsequent `return` expressions are inferred against it. **数组声明**:编译器尝试在一个数组声明中寻找一个最小化的类型。连接到常用基本类型(第3.5.5节)查看细节。 > **Array declaration:** The compiler tries to find a minimal type between all given types in an array declaration. Refer to Common Base Type (Section 3.5.5) for details. **对象声明**:如果一个对象被声明为一个特定类型,编译器统一每个指定的字段类型到每个期待的字段类型。 > **Object declaration**: If an object is declared “against” a given type, the compiler unifies each given field type with each expected field type. **操作符合一**:某些操作符期待特定的类型,指定的类型被对应统一。例如,表达式 a $$ b 统一a 和 b 为 Bool类型,表达式 a == b 统一a为b。 > **Operator unification**: Certain operators expect certain types which the given types are unified against. For instance, the expression a && b unifies both a and b with Bool and the expression a == b unifies a with b.