1
$\begingroup$

I'm wondering how to do the following:

    expr = L + R;

    foo[L_, R_] := expr;

    foo[1, 2]


(* L + R *)

and have it substitute the function variables into the expression. I realize that I could create dummy variables and do it like

foo[l_, r_] := expr /. L->l /. R->r

but my actual expression has a lot of free variables, and so I would like to know if there is a simpler way.

$\endgroup$
  • 3
    $\begingroup$ Check out Evaluate. $\endgroup$ – chuy Jan 21 '14 at 17:45
  • $\begingroup$ foo[L_,R_]=expr; The := is delayed evaluation which is usually correct but not in this precise case. $\endgroup$ – Ymareth Jan 21 '14 at 18:30
  • $\begingroup$ Use = instead of :=. It's not necessary to Evaluate IMO because it would be completely equivalent to just using =. I'd consider this question a duplicate of What is the difference between Set and SetDelayed?. $\endgroup$ – Szabolcs Jan 21 '14 at 19:30
1
$\begingroup$

As noted in the comments, use Set (=) instead of SetDelayed (:=) while making sure that L and R have no value assigned:

expr = L+R
foo[L_, R_] = expr

foo[1, 2]
(* ==> 3 *)
$\endgroup$
  • $\begingroup$ I went ahead and changed this, since it was community wiki. I think Evaluate would be completely equivalent to just using Set here. Hope you don't mind, please check the edit. $\endgroup$ – Szabolcs Jan 21 '14 at 19:32
  • $\begingroup$ @Szabolcs Sure, even if these were not CW I welcome good edits:) $\endgroup$ – Ajasja Jan 21 '14 at 20:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.