0
$\begingroup$

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.

enter image description here

$\endgroup$
  • $\begingroup$ See here. $\endgroup$ – march Mar 4 '16 at 21:35
2
$\begingroup$

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

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.

$\endgroup$
  • $\begingroup$ (+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. $\endgroup$ – H. R. Mar 4 '16 at 21:38

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.