2
$\begingroup$

Why does the function EER[1,2] have a different value than the function EERR[1,2]? Isn't the entry Kx[x, y] equivalent to this Kx[Sequence @@ var]? How to write EERR[Sequence @@ varr] so that it produces the same number as this EER[x_, y_]?

ClearAll["Global`*"]
Kx[x_, y_] := x^2 + y;
var = {x, y};
varr = Pattern[#, Blank[]] & /@ var;
Px[x1_, y1_] := x1^3 - y1;
var1 = {x1, y1};
EER[x_, y_] := Kx[x, y] + Px[x, y];
EER[1, 2]
(*2*)
EERR[Sequence @@ varr] := Kx[Sequence @@ var] + Px[Sequence @@ var];
EERR[1, 2]
(*x^2 + x^3*)
$\endgroup$
3
  • $\begingroup$ You need to Evaluate the RHS of EERR (in the definition). $\endgroup$ Commented May 26, 2023 at 11:42
  • $\begingroup$ @Alan, thanks! Could you please show $\endgroup$ Commented May 26, 2023 at 11:46
  • 1
    $\begingroup$ EERR[Sequence @@ varr] := Evaluate[Kx[Sequence @@ var] + Px[Sequence @@ var]]; $\endgroup$ Commented May 26, 2023 at 13:15

2 Answers 2

2
$\begingroup$

One recipe:

With[{var = var},
 EERRM[Sequence @@ varr] := (Kx @@ var) + (Px @@ var)
 ]
EERRM[1,2]

(* 2 *)

or, as you used

With[{var = var}, 
 EERRR[Sequence @@ varr] := 
   Kx[Sequence @@ var] + Px[Sequence @@ var];
 ]

EERRR[1,2]

(* 2 *)

$\endgroup$
3
  • $\begingroup$ Thank you very much! Сould you please explain this construct why it doesn't work without With (it's not a very obvious structure) $\endgroup$ Commented May 26, 2023 at 12:41
  • 1
    $\begingroup$ @MamMam The real problem here is not a sequence (the title therefore is misleading), but localization of variables. Usually in the definition of function one has to have same name for pattern and variable it represents, i.e. f[x_]:=x. But in your case your have f[varr_]:=var, which are different. Therefore your have to "insert" in the definition correct variables. This is most easily to do with With[] construction, which replaces all occurrences of var before evaluating its body. $\endgroup$ Commented May 26, 2023 at 13:02
  • $\begingroup$ Thanks for the explanation! $\endgroup$ Commented May 26, 2023 at 13:09
2
$\begingroup$

Here's your definition for EERR:

EERR[Sequence @@ varr] := Kx[Sequence @@ var] + Px[Sequence @@ var]

How does that get stored as a replacement rule? You can find out by looking at DownValues:

DownValues[EERR]

{HoldPattern[EERR[x_, y_]] :> Kx[Sequence @@ var] + Px[Sequence @@ var]}

It held the right-hand side completely unevaluated, but it did evaluate the left-hand side. And notice that x and y do not show up on the right hand side. So, when it goes to apply this rule, it won't do any replacements. So, it will go on to evaluate the right-hand side as-is.

You can force evaluation:

EERR[Sequence @@ varr] := Evaluate[Kx[Sequence @@ var] + Px[Sequence @@ var]]

And now...

DownValues[EERR]

{HoldPattern[EERR[x_, y_]] :> x^2 + x^3}

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.