Constructors create values for user-defined datatypes (Algebraic Datatypes).
Name ( Exp₁, Exp₂, ... )
|...||Depends on ADT declaration|
Constructors are created using the Call notation.
In ordinary programming languages record types or classes exist to introduce a new type name for a collection of related, named, values and to provide access to the elements of such a collection through their name.
In Rascal, AlgebraicDataTypes provide this facility. They have to be declared, see Algebraic Data Type, and then values can be created using calls to the declared constructor functions. The constructor Name should correspond (regarding name, arity and argument types) to one of the alternatives in the ADT declaration.
First, the actual parameter expressions Expᵢ are evaluated resulting in values Vᵢ. Next, a data value is constructed in accordance with the declared data type using the values Vᵢ as arguments for the constructor. This data value is used as value of the constructor. Constructors are functions that can be used in all contexts where functions can be used.
Observe that the syntax of a constructor is identical to the syntax of an function Call.
Also, all instances of Constructors are instances of Node values. This means that the generic
operations on Node also work on Constructor. If the Algebraic Data Type provides more precies types than
value for fields or keyword fields of a constructor, then the Node operations are checked using these more precise types, both statically and at run-time.
First, define a datatype
WF for word frequencies:
rascal>data WF = wf(str word, int freq);
Then construct a new
WF value by calling the constructor
wf with appropriate arguments:
Constructors with keyword parameters are also interesting:
>>>>>>> = rectangle(int width, int height, int area=width * height);
rascal>x = rectangle(100,200, area=100000);
rascal>y = rectangle(100,200);