Substituting a Value into an Expression

I am new to Mathematica so pardon me for the elementary question.

Can some one kindly explain that what is happening in the simple code below?

The With command does not work in the first case but it works in the second one. I don't understand why this happens.

• See here. – march Mar 4 '16 at 21:35

You can get the desired result by evaluating the expression within With using

    With[{y = 1}, Evaluate[g]]
(*10*)


Alternatively you can directly substitute any value $y$ in the expression using ReplaceAll

    g /. y -> 1
(*10*)

• Or, define g with set delayed rather than set: g:=y^2+5 y + 4 – bill s Mar 4 '16 at 21:34
• (+1) Thanks for the nice guide. And what is the reason that the above does not work? – Hosein Rahnama Mar 4 '16 at 21:35
• @H.R. see below ;-) Marchi was a few seconds faster than me... – mgamer Mar 4 '16 at 21:36

The With command has the attribute "HoldAll", so g is not evaluated. You can force evaluation with

With[{y = 1}, Evaluate @ ReleaseHold @ g]


but the more easy ways is to do

g /. y -> 1


Or simply define a function of y (which is probably what you want):

f[y_] := y^2 + 5 y + 4


then simply f[1] gives what you want.

• (+1) Thanks for the answer. I knew about defining pure functions but I wanted to know the other way. :) Your answer was useful in the sense that it released that why my code was not working. The problem was the attribute HoldAll. – Hosein Rahnama Mar 4 '16 at 21:38