0

It might be a trivial question but I haven't been able to find solution myself. Suppose that I have a calculation whose rather long output that is dependent in some variable e.g. x, I want it to be the body of a newly defined function. Schematically, what I would like is

In[1]:=  SomethingIsDone[...]
Out[1]:= (...really long expression dependent on x)
In[3]:=  f[x_]:= % ;

But the problem is that the above doesn't work. Any ideas?

hal
  • 783
  • 3
  • 14
  • 3
    Why can't you just do f[x_] = SomethingIsDone[...]? (Use Set (=) instead of SetDelayed (:=))? – march Feb 25 '20 at 17:35
  • Because I wanted to be evaluated every time that I call it. Furthermore, I don't want each time that I call the function f, to perform the SomethingIDone[...]. It's not efficient. – hal Feb 25 '20 at 17:54
  • Actually, maybe you are right. Essentially I want to define it immediately (because of %), so the only way to do it is with Set and not with SetDelayed. Maybe this is the reason that so far it didn't work... – hal Feb 25 '20 at 18:04

1 Answers1

2

Indeed as march comments in this case you can just use Set e.g.

FlowPolynomial[WheelGraph[9], x];

f[x_] = %;

?f

Global`f

f[x_] = 254 - 1023 x + 1792 x^2 - 1792 x^3 + 1120 x^4 - 448 x^5 + 112 x^6 - 16 x^7 + x^8

We could also use SetDelayed and Evaluate to effect the same thing:

FlowPolynomial[WheelGraph[9], x];

g[x_] := Evaluate[%];    (* Evaluate must wrap the entire right hand side *)

?g

Global`g

g[x_] := 254 - 1023 x + 1792 x^2 - 1792 x^3 + 1120 x^4 - 448 x^5 + 112 x^6 - 16 x^7 + x^8

Observe that in each case we have created a function that does not call FlowPolynomial when it is evaluated. Observe also that once defined either function can coexist with a global assignment to x:

x = "Fail!";  (* try to make the definitions fail *)

f[5]
g[5]
6564

6564

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • I think that g[x_] := Evaluate[...] is an abomination that is better not mentioned before teaching the proper distinction between Set and SetDelayed. – Roman Feb 25 '20 at 21:16
  • @Roman My intent was to show the similarity of these constructs as it seems to me the OP was for whatever reason hesitant to use Set, perhaps because someone told him to always use := for function definitions. How would you teach this? – Mr.Wizard Feb 25 '20 at 22:00
  • I'd teach it by making an analogy to something that's already familiar. SetDelayed is a soft link and Set is a hard link. SetDelayed is a cooking recipe and Set is an MRE. SetDelayed is the map, and Set is the territory. Both are useful; one does not replace the other. Help the student acquire multiple concepts of assignment. – Roman Feb 26 '20 at 06:55