fortran-lang.org's Quickstart Tutorial gives the following example for a parameterised derived type:
type, public :: t_matrix(rows, cols, k)
integer, len :: rows, cols
integer, kind :: k = kind(0.0)
real(kind=k), dimension(rows, cols) :: values
end type
It notes parameters must be len
or kind
parameters, or both. The guide doesn't provide an explicit definition of these. My rough understanding is that they're special integers used in dimension()
or for the kind of a type.
len
and kind
parameters?len
and kind
attributes only apply to integer declarations?Our usual friends of the intrinsic data types have type parameters, and these are a direct analogue of the parameters one sees in a parameterized derived type.
Consider a character entity:
character(len=55, kind=SELECTED_CHAR_KIND('ASCII')) :: name
This has a length type parameter (value 55) and kind type parameter (value corresponding to ASCII representation).
We know that we can have a character entity that can change in length during execution (deferred):
character(len=:, kind=SELECTED_CHAR_KIND('ASCII')), allocatable :: name
Or indeed have a length that's implied or assumed. What we also know is that the kind parameter can never change. Just like the kind of a real, integer, or complex entity.
That's about all the motivation we need to understand parameters in derived types.
But to go on...
A length-type parameter of a derived type is motivated by being like a character's length which may vary, but it can be used in many other ways. A kind-type parameter of a derived type is motivated by being like a character's kind, but it can also be used in many other ways:
type t(len, kind, species)
integer, len :: len
integer, kind :: kind, species
character(len=kind) :: name(kind, len)
end type t
More formally, the kind-type parameters in a derived type definition can feature in constant and specification expressions in that definition, but length-type parameters may appear in specification expressions and not in constant expressions.
When an entity is declared as a parameterized type, any kind-type parameter must be given by a constant expression.
Finally, yes: a type parameter must be an integer, but itself can be an integer of any kind. The kind
and len
specify whether the type parameter is of kind or length type.