We will briefly describe simple parametrized classes here so that they may be used in examples through the rest of the text. For a full description of parametrized classes, please see the chapter on Parametrized Classes.
A Sather class may have various type parameters, which are basically place holders for types which are specified when the class is actually used. This allows us to write code that is generic and can be used with a different types. By convention, these type parameters are given names like T or TP. We show below a class TUP, which holds pairs of objects. Since we would like to be able to hold objects of any types, we just specify type parameters, T1 and T2. These parameters are place-holders, which must be set to actual honest-to-goodness concrete classes when the TUP is actually used
class TUP{T1,T2} is -- Simple version of the library tuple class attr t1:T1; attr t2:T2; create(t1:T1, t2:T2): SAME is -- Standard create routine. Arguments use the type parameters res ::= new; -- Using static type inference - new returns SAME res.t1 := t1; -- The types of res.t1 and the argument t1 -- are both T1 so the assignment is legal res.t2 := t2; return res; end; end; |
We can now create a tuple object that holds, for instance, a pair consisting of a string and an integer:
t ::= #TUP{INT,STR}(5,"this"); -- Create a new tuple. -- Uses ::= to determine the type of 't' #OUT + t.t1 + "\n"; |
A standard parametrized class is the array class, ARRAY{T}. (See unnamedlink for more details). When an array is actually used to hold objects, the type parameter must be instantiated to indicate the kind of objects being held.
a:ARRAY{INT} := |2,5,7|; -- Special syntax for initializing an array with values 2,5,7 #OUT+a[1]; -- Return the second element of the array |
For example, arrays are used to pass in the arguments to a program into the main procedure.
main(args:ARRAY{STR}) is #OUT + args[0]; -- On unix, args[0] is the name of the program end; |
We can hold a collection of points using an array, as follows
a:ARRAY{POINT} := #(3); a[0] := #POINT(0.0,0.0); a[1] := #POINT(0.0,1.0); a[2] := #POINT(2.0,2.0); |