Items of type TEXT are a curious hybrid between arrays and lists. It is possible to grow and shrink them, like a list, but it is also possible to index into them using the interface functions GetChar and Sub.
Write a procedure to return the reverse of a string.
Input is an item of type TEXT, output is an item of type TEXT:
PROCEDURE Reverse(str : TEXT) : TEXT
Treating the string like an array, do we wish to process every element? If so, then a FOR-loop is called for, such as:
VAR
reversed : TEXT := "";
BEGIN
FOR i := 0 TO Text.Length(str) - 1 DO
reversed := Text.FromChar(Text.GetChar(str,i)) & reversed;
END;
RETURN reversed;
END Reverse;
Or
VAR
reversed : TEXT := "";
BEGIN
FOR i := Text.Length(str) - 1 TO 0 DO
reversed := reversed & Text.FromChar(Text.GetChar(str,i));
END;
RETURN reversed;
END Reverse;
Can you write a recursive version of both of these? Remember to think about what the result will be if the string is empty, and then what to do with the first character and a recursive application to the rest of the string. You can find the `Tail' of the string with the following expression:
Text.Sub(str,1,Text.Length(str)-1);
To Previous PageTo Overview
To Next Page