UcenlyOpen in the app

Mathematical Applications · BE5B15MAA · Topic 10 of 13

Functions in Mathematica: piecewise functions, overloaded functions, tracing the evaluation

Week 10. One symbol can have several definitions; conditions pick between them and Trace shows what happened.

Open the interactive lesson

Key ideas

Conditions and piecewise definitions

A condition /; restricts a rule: f[x_]:=x/;x<=1 and f[x_]:=2−x^2/;x>1 make a piecewise function. Which[x<1,x,x>=1,2−x^2] and Piecewise do the same in one expression. Conditional rules can also call themselves, for example to extend a function periodically: f[x_]:=f[x−2]/;x>1.

Overloaded definitions

Several definitions of f can coexist. They differ by the number of arguments (f[x_] and f[x_,y_]), by a list pattern (f[{x_,y_}]), by a type (f[x_Integer]) or by a literal (f[1]). Mathematica tries the more specific definitions first, and keeps the order of definition among definitions it cannot rank.

Tracing and memoization

Trace[a[3]] lists the steps of an evaluation. The recursive definition a[n_]:=n*a[n−1] with a[0]:=1 recomputes everything on every call and may hit $RecursionLimit; a[n_]:=a[n]=n*a[n−1] stores each value the first time it is computed (memoization), so Timing[Table[a[i],{i,1050}]] becomes fast.

In one line: Order your definitions from specific to general, and memoize a recursion with f[n_]:=f[n]=....

Sources

Written by Ucenly. Based on the BE5B15MAA course materials: