Question: does Maple have immediate vs. delayed proc defintion?

In Mathematica, one can define a function 2 ways. Using delayed evaluation of its RHS (which is same as proc() in Maple) but also as immediate evaulation of its RHS.

In the immediate evaluation, what happens is that the RHS is evaulated first using normal evaluations, then the result of this evaluation becomes the new body of the function.

This can be very useful sometimes. For examle, if the RHS was a complicated integral, which can be evaluated immediatly and gives a result, which still depends on a parameter to fully evaluate, then this method saves having it to evaluate the full integral each time as with the case of delayed evaluation.

I do not know how to emulate immediate evaluation, but using a proc() in Maple. Here is a simple example to explain.

restart;
foo:=proc(n::integer)
     local r;
     r:=int(x*sin(n*x),x=0..Pi);
     r;
end proc;

(ps. I added the extra `r` there just for debuging. They are not needed)

Now when doing foo(3), then the integral will have to be computed each time for each `n`.

But If the integral was evaluated at time of the function definition, it will have the result of -(-1)^n*Pi/n and now when the function is called, then it will be much faster, since in effect the calling the function would be as if one typed

restart;
foo:=proc(n::integer)
     local r;
     r:=-(-1)^n*Pi/n;
     r;
end proc;

In Mathematica, I can do the above by defining a function using `=` instead of the delayed `:=`

foo[n] = Assuming[Element[n, Integers], Integrate[x Sin[n*x], {x, 0, Pi}]]

Now when I do f[3], it will actually use -(-1)^n*Pi/n as the body of the function since the RHS side of the function was evaluated immediatly at time the function was defined. This saves having to do the integral each time.

To make it work like in Maple, the one must make it delayed, like this

foo[n] := Assuming[Element[n, Integers], Integrate[x Sin[n*x], {x, 0, Pi}]]

How can one emulate the immediate evaluation of a proc() in Maple? If not the whole body, but may be a statment? as if one can do

restart; foo:=proc(n::integer) 
      local r; 
      r:=eval_now(int(x*sin(n*x),x=0..Pi)); #result of int is used in definition
      r; 
end proc;

so that the body of the proc will be evaluated as much as possible at time of definition? This can be much more efficient in some cases.

I know ofocurse I could write

foo:=int(x*sin(n*x),x=0..Pi) assuming n::integer;

and then use subs() to evaluate for different `n`. But I wanted to use proc().

 

Please Wait...