## Julia – 36 – tipi – 5

Continuo da qui, copio qui.

Tipi parametrici astratti
Parametric abstract type declarations declare a collection of abstract types, in much the same way:

With this declaration, `Pointy{T}` is a distinct abstract type for each type or integer value of `T`. As with parametric composite types, each such instance is a subtype of `Pointy`:

Parametric abstract types are invariant, much as parametric composite types are:

The notation `Pointy{<:Real}` can be used to express the Julia analogue of a covariant type, while `Pointy{>:Int}` the analogue of a contravariant type, but technically these represent sets of types (see UnionAll Types [prossimamente]).

Much as plain old abstract types serve to create a useful hierarchy of types over concrete types, parametric abstract types serve the same purpose with respect to parametric composite types. We could, for example, have declared `Point{T}` to be a subtype of `Pointy{T}` as follows:

Given such a declaration, for each choice of `T`, we have `Point{T}` as a subtype of `Pointy{T}`:

This relationship is also invariant:

What purpose do parametric abstract types like `Pointy` serve? Consider if we create a point-like implementation that only requires a single coordinate because the point is on the diagonal line `x = y`:

Now both `Point{Float64}` and `DiagPoint{Float64}` are implementations of the `Pointy{Float64}` abstraction, and similarly for every other possible choice of type `T`. This allows programming to a common interface shared by all `Pointy objects`, implemented for both `Point` and `DiagPoint`. This cannot be fully demonstrated, however, until we have introduced methods and dispatch in the next section, Methods [prossimamente].

There are situations where it may not make sense for type parameters to range freely over all possible types. In such situations, one can constrain the range of `T` like so:

Nota: questa dichiarazione va in conflitto con le precedenti, per cui occorre chiudere e riaprire la REPL.

With such a declaration, it is acceptable to use any type that is a subtype of `Real` in place of `T`, but not types that are not subtypes of `Real`:

Type parameters for parametric composite types can be restricted in the same manner:

To give a real-world example of how all this parametric type machinery can be useful, here is the actual definition of Julia’s `Rational` immutable type (except that we omit the constructor here for simplicity), representing an exact ratio of integers:

It only makes sense to take ratios of integer values, so the parameter type `T` is restricted to being a subtype of `Integer`, and a ratio of integers represents a value on the real number line, so any `Rational` is an instance of the `Real` abstraction.

Annunci
Posta un commento o usa questo indirizzo per il trackback.