![]() |
|
Navigation |
Synopsis Type parameters enable parameterized types.
Syntax
& Name
Description A type parameter may occur at every syntactic position where a type is required and turns an ordinary type into a parameterized type.
Parameterized types are used to define polymorphic functions and data types, i.e., functions and data types that are applicable for more than one type. Type parameters are bound to an actual type when the function or data type is applied and further uses of the type parameter are consistently replaced by the actual type.
The following syntactic positions are binding occurrences for type parameters:
Examples Let's consider a small example of the use of function parameters in a function declaration, see Function
for more details on function declarations.
The following function
swap returns a tuple in which its arguments are swapped and can be applied to arbitrary values
in a type safe manner:
rascal>tuple[&B, &A] swap(&A a, &B b) { return <b, a>; } tuple[&B,&A] (&A, &B): tuple[&B,&A] swap(&A, &B); rascal>swap(1,2); tuple[int,int]: <2,1> rascal>swap("abc", 3); tuple[int,str]: <3,"abc">Observe that the type parameters that are used in the return type should be defined in the declarations of the formal parameter of the function. An Alias declaration may also be parameterized. So we can generalize graphs as follows: rascal>alias Graph[&Node] = rel[&Node, &Node]; ok rascal>Graph[int] GI = {<1,2>, <3,4>, <4,1>}; Graph[int]: { <4,1>, <1,2>, <3,4> } rascal>Graph[str] GS = {<"a", "b">, <"c","d">, <"d", "a">}; Graph[str]: { <"d","a">, <"a","b">, <"c","d"> }The type parameters that are used in the type in the right part of the alias declaration should be defined in the left part of the alias definition. ![]() |