1
$\begingroup$

I have an expression:

exp = a+b+c

and a list containing all the symbols of my expression:

syms = {a,b,c}

and I would like to replace the symbols with numerical values. I have a list containing the numerical values:

val = {1,2,3}

and I would like to perform something like this:

 exp/.syms->val

to get: 1+2+3

But this doesn't work. Do you know why?

$\endgroup$
1

2 Answers 2

2
$\begingroup$

You need to do

  exp /. Thread[syms ->  val]
  (* 6 *)

the reason exp /. syms -> val does not work can be seen by doing trace:

  Trace[exp /. syms ->  val]

Mathematica graphics

You can see it was looking for a+b+c/.{a,b,c}->{1,2,3} and since there is no pattern {a,b,c} then it does not work.

With Thread, you basically break it to a->1,b->2,c->3 then it works.

$\endgroup$
1
$\begingroup$

to get: 1+2+3

you can use any of:

exp /. Thread[syms -> (Defer /@ val)]
exp /. Thread[syms -> (HoldForm /@ val)]
Defer[Evaluate@exp] /. Thread[syms -> val]
HoldForm[Evaluate@exp] /. Thread[syms -> val]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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