Use of a StringBuffer is much more efficient that the naive approach shown here.
Here is another, more subtle example.
>
|
G := proc()
description "extremely inefficient string concatenator";
local r;
r := proc()
if nargs = 0 then
""
elif nargs = 1 then
args[ 1 ]
else
cat( args[ 1 ], procname( args[ 2 .. -1 ] ) )
end if
end proc;
r( args )
end proc:
|
This can be transformed into an O(1) algorithm by passing a string buffer to the recursive calls.
>
|
F := proc()
description "efficient version of G";
local b, r;
b := StringTools:-StringBuffer();
r := proc()
if nargs = 1 then
b:-append( args[ 1 ] )
else
b:-append( args[ 1 ] );
procname( args[ 2 .. -1 ] )
end if
end proc;
r( args ):-value()
end proc:
|
Here is a procedure to read the contents of a file, one line at a time, applying a given filtering operation to each line.
>
|
FilterFile := proc( fname::string, filter )
local b, line;
b := StringTools:-StringBuffer();
do
line := readline( fname );
if line = 0 then break end if;
b:-append( filter( line ) )
end do;
b:-value()
end proc:
|