UcenlyOpen in the app

Mathematical Applications · BE5B15MAA · Topic 9 of 13

Functions in Mathematica: Blank, Set, SetDelayed, Module

Week 9. A function definition is a permanent replacement rule; the difference between = and := is when the right-hand side is evaluated.

Open the interactive lesson

Key ideas

Blank patterns

f[x_]:=x+1+x says: whenever f[anything] appears, replace it by anything+1+anything. x_ is short for x:_, the name x is local to the rule, and the pattern can be restricted: x_Integer needs an integer, x_?test needs test[x] to give True.

Set versus SetDelayed

= evaluates the right-hand side once, at definition time; := keeps it unevaluated and evaluates it at every call. After a=RandomReal[] the symbol a keeps one number, after b:=RandomReal[] each use of b draws a new one. For f[x_]=Integrate[2x,x] the integral is done once and f[1] is 1, whereas f[x_]:=Integrate[2x,x] substitutes 1 for x everywhere, also in the integration variable, and returns a meaningless integral.

Module and local variables

If a global x has a value when a Set definition is made, that value is used on the right-hand side, so use ClearAll or Module. Module[{sol,x},body] makes x local: f[a_]:=Module[{sol,x},sol=FindRoot[Cos[x]==a*x,{x,0}];x/.sol] leaves any global x alone.

In one line: Use := by default; use = only when you want the right-hand side computed now, and keep helper symbols inside Module.

Sources

Written by Ucenly. Based on the BE5B15MAA course materials: