0

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

Hosein Rahnama
  • 1,727
  • 1
  • 15
  • 29

2 Answers2

6

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*)
Marchi
  • 1,838
  • 9
  • 7
4

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.

mgamer
  • 5,593
  • 18
  • 26
  • (+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 04 '16 at 21:38