UcenlyOpen in the app

Mathematical Applications · BE5B15MAA · Topic 8 of 13

Principles of procedural, functional and pattern-oriented programming

Week 8. The same task can be written with loops, with functions applied to lists, or with replacement rules.

Open the interactive lesson

Key ideas

Three styles

Procedural code uses Do, While, For and If with local variables from Module. Functional code needs no loops: Map (/@) applies a function to every element, Apply (@@) puts the elements in as arguments and Nest applies a function repeatedly. Rule-based code adds replacement rules and patterns, for example x_ for anything and _Integer for an integer.

Pure functions

Function[x,x^2+x][5] gives 30; the short form #^3&[3] gives 27, where # is the argument and & ends the function. A function can return a function: Function[y,Function[x,x^y]][7][4] is 4^7=16384. A function can also be passed as an argument.

Replacement rules

expr /. rule replaces every match once; with a flat list of rules the first applicable one wins, so x/.{x->Pi,x->E} is Pi. A list of lists of rules gives a list of results: x/.{{x->Pi},{x->E}} is {Pi,E}. Solve returns such lists of rules, and x/.Solve[...] turns them into values.

In one line: Pick the style that says the task shortest: Map and Nest replace loops, rules replace if-chains.

Sources

Written by Ucenly. Based on the BE5B15MAA course materials: