MathGroup Archive 1998

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

Search the Archive

Re: strange function that defines a function---how do I do it?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg15223] Re: strange function that defines a function---how do I do it?
  • From: "Allan Hayes" <hay at haystack.demon.co.uk>
  • Date: Wed, 23 Dec 1998 01:04:00 -0500
  • References: <75no5e$sgj@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Benjamin Lotto wrote in message <75no5e$sgj at smc.vnet.net>...
>Working with Mathematica 3.0:
>
>Suppose I define
>
>   makefunction[var_, expr_]:=f[var_?NumberQ]:=NIntegrate[expr,{x,0,1}]
>
>Then I can do something like
>
>   z=x^2
>   makefunction[x,z]
>
>and it will be just as if I typed
>
>   f[x_?NumberQ]:=NIntegrate[x^2,{x,0,1}]
>
>In fact, entering
>
>   ?f
>
>at this point yields
>
>   "Global`f"
>
>   f[(x_)?NumberQ] := NIntegrate[x^2, {x, 0, 1}]
>
>OK, now suppose I have a list of variables  x1  up through  xn.  Suppose
>they're in a list:
>
>   list={x1,x2,...,xn}
>
>I want something like "makefunction" above so that when I type
>
>   makefunction[list,expr]
>
>it will be just as if I typed
>
>   f[x1_?NumberQ,x2_?NumberQ,...,xn_?NumberQ]:=expr
>
>analogous to the above.  Can anyone help me?
>
>Thanks in advance.  Y'all out there have been very helpful in the past.
>

Benjamin:

One way

Clear["`*"]

makefunction[var_, expr_] :=
  Block[{f, SetDelayed}, f @@ (#_?NumberQ & /@ var) := expr]

list = {x1, x2};

makefunction[list, 6]

Check

?f

Global`f
f[x1 _?NumberQ, x2 _?NumberQ] := 6


We can get problems if f is not blocked and there are no tests

Clear["`*"]

makefunction[var_, expr_] := Block[{SetDelayed}, f @@ (#_ & /@ var) :=
expr]

list = {x1, x2};

makefunction[list, 6]

?f

    Global`f
    f[x1 _, x2 _] := 6

But if we define a second time then  f[x1_,x_2] evaluates to 6 before
the setting is made and the definition fails:

makefunction[list, 6]

    SetDelayed::"setraw": "Cannot assign to raw object 6."

    $Failed

Allan

---------------------
Allan Hayes
Mathematica Training and Consulting
www.haystack.demon.co.uk
hay at haystack.demon.co.uk
Voice: +44 (0)116 271 4198
Fax: +44 (0)870 164 0565





  • Prev by Date: Launching a front end notebook from a Kernel (mathlink & Borland C++) (fwd)
  • Next by Date: Q: extra carriage returns in OutputForm[] output?
  • Previous by thread: Re: strange function that defines a function---how do I do it?
  • Next by thread: Re: strange function that defines a function---how do I do it?