Structural type system

From Wikipedia, the free encyclopedia

A structural type system is a major class of type system, in which type compatibility and equivalence are determined by the type's structure, and not through explicit declarations. Structural systems are used to determine if types are equivalent, as well as if a type is a subtype of another. It contrasts with nominative systems, where comparisons are based on explicit declarations or the names of the types.

In structural typing, two objects or terms are considered to have compatible types if the types have identical structure. Depending on the semantics of the language, this generally means that for each feature within a type, there must be a corresponding and identical feature in the other type. Some languages may differ on the details (such as whether the features must match in name).

Haskell, ML and Whiteoak are examples of structurally-typed languages.

In languages which support subtype polymorphism, a similar dichotomy can be formed based on how the subtype relationship is defined. One type is a subtype of another if and only if it contains all the features of the base type (or subtypes thereof); the subtype may contain additional features (such as members not present in the base type, or stronger invariants).

Structural subtyping is arguably more flexible than nominative subtyping, as it permits the creation of ad hoc types and interfaces; in particular, it permits creation of a type which is a supertype of an existing type T, without modifying the definition of T. However this may not be desirable where the programmer wishes to create closed abstractions.

A pitfall of structural typing versus nominative typing is that two separately defined types intended for different purposes, each consisting of a pair of numbers, could be considered the same type by the type system, simply because they happen to have identical structure. One way this can be avoided is by creating one algebraic data type for one use of the pair and another algebraic data type for the other use.

[edit] Duck typing

One interesting type scheme, which behaves similarly to structural typing, is duck typing. Duck typing differs from structural typing in that only the part of the structure accessed at run time is checked for compatibility.

[edit] External links

Languages