MathGroup Archive 2007

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Function as an argument

  • To: mathgroup at
  • Subject: [mg76751] Re: Function as an argument
  • From: Bill Rowe <readnewsciv at>
  • Date: Sat, 26 May 2007 04:52:33 -0400 (EDT)

On 5/25/07 at 6:20 AM, dxdydzdu at (dXdYdZdu) wrote:

>Hi, I have problem. I want to do something like this:
>ss[x_] = 2 + x^3 ; MyFunction[expression_] := Module[{},

>Calling MyFunction[ss] will produce 10 and this is working case.

>but this is what I can not do:

>MyFunction[2 + x^3]

>Is there a way to make this to work as well?

Yes, instead of writing an expression with an explicitly named
variable write it as a pure function, i.e., as you wrote
MyFunction this works

In[16]:= MyFunction[2 + #^3 &]

Out[16]= 10

There are other alternatives, for example

In[17]:= Clear[MyFunction];
MyFunction[expression_, var_: x] := expression /. var -> 2

In[19]:= MyFunction[2 + x^3]

Out[19]= 10

and note this version does the right thing even if you use a
different variable name, i.e.,

In[20]:= MyFunction[2 + y^3, y]

Out[20]= 10

Note, since you aren't using local variables and have no code to
execute after expression is evaluated neither Module nor Return
are needed. That is your design could be written as

MyFunction[expression_] := expression[2]
To reply via email subtract one hundred and four

  • Prev by Date: Re: asymptotics
  • Next by Date: Re: matrices with arbitrary dimensionality
  • Previous by thread: Re: Function as an argument
  • Next by thread: Running math in shell with notebook as output