Using a function as an input to a procedure?



Jaime's example uses EXPRESSIONS  like x^2.
Alasdair's question may be about FUNCTIONS like f,  where f(x):=x^2.


If you pass f, a symbol, into a function, you can be sure of using that
(instead of some other f)
by using  apply(f,[y]).     Then you should get y^2.

Another trick is to use some strange name internally for f so that it won't
conflict, you hope,
with any other name.  (The issue has to do with "dynamic scope" in
programming languages).
e.g.  dt(fff,a,b):= ....  will not grab some other name.

more explanation...

  if you wrote   dt(sin,a,b):= ... sin(a) ...   which function "sin" would
you expect to call?
Maxima will call the system function.

RJF

 

> -----Original Message-----
> From: maxima-bounces at math.utexas.edu 
> [mailto:maxima-bounces at math.utexas.edu] On Behalf Of Jaime Villate
> Sent: Friday, May 02, 2008 3:20 AM
> To: Alasdair McAndrew
> Cc: maxima list
> Subject: Re: [Maxima] Using a function as an input to a procedure?
> 
> 
> On Fri, 2008-05-02 at 19:25 +1000, Alasdair McAndrew wrote:
> > one thing I need to do is to create a small procedure which produces
> > the difference between an integral and its trapezoidal 
> approximation;
> > such as:
> > 
> > dt(f,a,b):=float(abs(integrate(f(s),s,a,b)-(f(a)+f(b))*(b-a)/2));
> > 
> > But this doesn't work; or at least, when I tried it earlier I got a
> > "Too many contexts" error message.  Is there an approved 
> technique for
> > writing a procedure which uses functions as inputs?
> 
> I don't know if there is an approved technique, but this is 
> something I
> do in all of the functions in the package dynamics; I tried several
> different methods and the one I liked the most was the following:
> 
> dt(f,a,b) :=
>   block  
>  ([intg, approx, var, numer: true, float: true],
>   if length(listofvars(f)) # 1 then
>      error("fun should depend on one variable")
>   else
>      var: listofvars(f),
>   intg: integrate(f,var[1],a,b),
>   approx: (ev(f, var[1]=a) + ev(f, var[1]=b))*(b - a)/2,
>   abs(intg - approx))$
> 
> 
> Example of its use:
> 
> (%i16) dt(x^2,3,5);
> (%o16) 1.333333333333336
> (%i17) f(x):= 3*x-2$
> (%i18) dt(f(u),3,5);
> (%o18) 0.0
> 
> I hope this helps.
> Jaime
> 
> _______________________________________________
> Maxima mailing list
> Maxima at math.utexas.edu
> http://www.math.utexas.edu/mailman/listinfo/maxima
>