Return to the FAQ on functions and procedures
 

Examples of functions and procedures in Maple

Here is one use of global variables....a list of data that you wish to use inside the function, but the declaration is made in a command that is not part of the function.

> months:=[January,February,March,April,May,June,July,August,September,October,November,December]:

> sdate2ldate:=proc(mth,day,year) global months;
months[mth], day, year+1900;
end:

> sdate2ldate(12,7,41);

[Maple Math]






Here is an example of a function that uses the if-then, for do, and RETURN.
Find a solution to the equations in x^3 + 3*x*y + y^2 = 17 mod n....where n is any integer > 1. We will do this by checking all possible values for x and y between 0 and n-1 (notice that this method for solving this equation may take n^2 operations).

> findsolns:=proc(n) local x,y;
for x from 0 to n-1 do
for y from 0 to n-1 do
if evalb(((x^3+3*x*y+y^2-17) mod n) = 0) then
RETURN([x,y]);
fi;
od;
od;
"no solution";
end:

> findsolns(29);

[Maple Math]

> (5^3+3*5*19+19^2) mod 29;

[Maple Math]





Take a list and repeat everything in it 3 times. We want to write a function that accepts a list and returns another list. We will write this function in 4 different ways...ALL four do exactly the same thing.

> rep3times1:=proc(lst) local i;
[seq((lst[i],lst[i],lst[i]),i=1..nops(lst))];
end:

> rep3times2:=proc(lst) local r3t,i;
r3t:=proc(a);
a,a,a;
end;
[seq(r3t(lst[i]),i=1..nops(lst))];
end:

> rep3times3:=proc(lst) local r3t,i,out,j;
out:=NULL;
for i from 1 to nops(lst) do
out:=out,seq(lst[i],j=1..3);
od;
[out];
end:

> rep3times4:=lst->map(a->(a,a,a),lst):

> rep3times1([5,4,abc,2,1]);

[Maple Math]

> rep3times2([5,4,abc,2,1]);

[Maple Math]

> rep3times3([5,4,abc,2,1]);

[Maple Math]

> rep3times4([5,4,abc,2,1]);

[Maple Math]





Here is a couple of examples of the function rotntimes at work. Notice what is the output when the definition is given with a semi-colon at the end instead of a colon. Maple's representation of the function is shown. No picture is produced until we actually use the function.

> rotntimes:=proc(pic, n) local i;
plots[display]([seq(plottools[rotate](pic,2*Pi/n*i),i=1..n)]);
end;

[Maple Math]

> rotntimes(plot(cos(x),x=0..2*Pi,axes=none,color=green),12);

[Maple Plot]

> ?arrow

> rotntimes(plots[display](plottools[arrow]([4,4], [10,10], .4, .8, .1, color=blue),axes=none),55);

[Maple Plot]

>
 

Return to the FAQ on functions and procedures