Mathematica programming tools

Localizing variables

Basic use

x = 1

Print[x]

Block[{x}, Print[x]]

Module[{x}, Print[x]]

With[{x}, Print[x]]

x

Block[{x = 2}, Print[x]]

Module[{x = 3}, Print[x]]

With[{x = 4}, Print[x]]

Block[{x = 2}, x = 5; Print[x]]

Module[{x = 3}, x = 5; Print[x]]

With[{x = 4}, x = 5; Print[x]]

Clear[x]

Restricting arguments

Clear[f, x]

Blank[]

Pattern[x, Blank[]]

Pattern[x, Blank[Integer]]

Head[3]

Head[3. ]

Head[3 + I]

Head[1/3]

f[Pattern[x, Blank[]]] = x^2

f[2]

f1[n_] = n^2

f1[4]

f1[2.2]

f2[n_Integer] = n^2

f2[4]

f2[2.2]

Functions as arguments

Clear[g]

Function[x, x^2]

Function[x, x^2][2]

g = Function[x, x^2]

g[2]

Clear[f, myD]

myD[f_, 
        x_] := 
Module[{g}, 
g = 
          Function[x, f]; 
D[g[x], 
          x]
]

myD[x^2, x]

myD[f_, 
        x_] := 
Module[{g}, 
g = 
          Function[x, f]; 
D[g[x], 
          x]
]

myFTCevaluator[F_, x_, a_, 
        b_] := 
Module[{g}, 
g = 
          Function[x, F]; 
g[b] - g[a]]

myFTCevaluator[x^2, x, 1, 3]