Application Center - Maplesoft

App Preview:

Maple Programming: 4.8: Anonymous procedures

You can switch back to the summary page by clicking here.

Learn about Maple
Download Application


 

4.08.mws

Programming in Maple

Roger Kraft
Department of Mathematics, Computer Science, and Statistics
Purdue University Calumet

roger@calumet.purdue.edu

4.8. Anonymous procedures

When we define a procedure we almost always give it a name. But we do not have to. We can have unnamed procedures just as we can have unnamed functions or expressions. Unnamed procedures are called anonymous procedures . Here is an anonymous procedure that takes a string and a positive integer as input and returns the string truncated to the integer number of letters. (If you want to see how this procedure "works", convert the body of the procudure into an execution group and play with the execution group.)

>    proc(x::string, n::posint)

>      local i;

>      seq( x[i], i=1..n );

>      cat( % );

>    end;

proc (x::string, n::posint) local i; seq(x[i],i = 1 .. n); cat(%) end proc

Right now the procedure is anonymous. But we can still call this procedure.

>    %( "this is a long name", 11 );

We can give the procedure a name, so that it is no longer anonymous.

>    shorten := %%;

shorten := proc (x::string, n::posint) local i; seq(x[i],i = 1 .. n); cat(%) end proc

Now we can call the procedure by its new name.

>    shorten( "Aren't we having fun?", 15 );

Here is an anonymous procedure that reverses the letters in a string. The following command defines the anonymous procedure, calls it, and gives the result of the call a name, all in a single command.

>    x := proc(x::string)

>            local i;

>            cat(seq(x[-i], i=1..length(x)))

>         end( "try it out" );

x :=

Notice that the assignment operator was acting on the result of the call to the anonymous procedure. The procedure itself is still anonymous.

>    x;

>   

The last few commands were meant to emphasize that defining and naming a procedure are two distinct steps and procedures do not have to have names to be used. Anonymous procedures can be used anywhere anonymous functions can be used. But anonymous functions are more common than anonymous procedures.

>   

Exercise : Pick apart the two anonymous procedures from this section and make sure that you understand how they work. Try converting them into execution groups, so that you can see the results of each step in the procedure body.

>   

>   

>