Seed7 Example: Generic map function

Seed7 FAQ Manual Demo Screenshots Examples Libraries Algorithms Benchmarks Index Download GitHub Build Seed7 Links
Examples echo args file in string simple clock count words subtype map function generic func declare stmt template operator 3-way if
Examples Generic map function

A normal map function is defined for a specific array element type. To use a map function for arbitary types it must be defined with a template. A template can define the map function for a given array element type. For this purpose 'GENERIC_MAP_FUNCTION' uses the type parameter 'elementType':

const proc: GENERIC_MAP_FUNCTION (in type: elementType) is func
 local
 var type: arrayType is void;
 begin
 arrayType := array elementType;
 const func arrayType: doMap (in arrayType: anArray,
 inout elementType: aVariable, in func elementType: anExpression) is func
 result
 var arrayType: mappedArray is 0 times elementType.value;
 begin
 for aVariable range anArray do
 mappedArray &:= anExpression;
 end for;
 end func;
 end func;

The body of 'GENERIC_MAP_FUNCTION' contains a definition of 'doMap'. Seed7 templates must be instanciated explizit. E.g.:

GENERIC_MAP_FUNCTION(float);
GENERIC_MAP_FUNCTION(string);
GENERIC_MAP_FUNCTION(time);

Assume that 'word' is a string variable. Now

doMap([]("apple", "pear", "apricot", "melon"), word, word & "s")

will return

[]("apples", "pears", "apricots", "melons")

Other possible calls of 'doMap' are:

doMap([] (1.2, 2.3, 3.4), x, x + 1.0)
doMap(thing, word, "a " & word)
doMap(birthdays, z, z + 1 . YEARS)

AltStyle によって変換されたページ (->オリジナル) /