Writing a Wolfram Language Function
Writing a Wolfram Language Function
USEFUL TIPS
Learning Objectives
Learning Objectives
Useful Tips
Useful Tips
Localise variables within a computation
Add syntax information to a function
Give a function special attributes
Optional: learn about speed and efficiency
Add a progress monitor to a calculation
Extract information from a function
Learn about common coding pitfalls
Summary
Summary
Course Summary
Course Summary
Useful Tips
Useful Tips
Useful Tips
Useful Tips
Localisation
Localisation
A good practice for programming in general—not just for creating functions—is to localise variables wherever possible. There are three main functions for doing this: With, Module and Block. Each of these functions has a slightly different purpose, but for small tasks they are often interchangeable. Another function worth mentioning is DynamicModule, which is typically used for creating dynamic interfaces.
All of these functions share a common structure: a list of variables in the first argument and an expression (containing the variables) in the second argument.
With
With
Tech Note: Local Constants
With uses lexical scoping. It replaces its variables with their assigned values immediately, treating them like constants. Because of this, variables inside With cannot be reassigned:
With[{a=1},a=2]
With is particularly useful for setting up initial data.
Create a function that plots some random temporal data (note the reuse of initialData several times throughout the function):
ClearAll[plotData];plotData[noOfPoints_:100]:=,
With
{initialData=RandomFunction[ARProcess[{0.7},1],{1,noOfPoints}]},ListPlotinitialData,PlotRange->{{0,noOfPoints},MinMax[initialData]+{-1,1}},PlotLegends->Grid{{"Mean",Mean[initialData]},{"Range",First[Differences[MinMax[initialData]]]}},
;plotData[200]Module
Module
Module uses lexical scoping. It is generally the go-to function for localising variables. To ensure there are no symbol conflicts, it creates new temporary symbols for each of its variables:
{Module[{a},a],Module[{a},a]}
Module can be used to localise small—so-called “helper”—functions, which can then be used inside larger functions.
Create a function that plots a distribution of Titanic passengers by age:
ClearAll[plotTitanicData];plotTitanicData[{minAge_:20,maxAge_:30}]:=With[{data=Normal[ExampleData[{"Dataset","Titanic"}]]},
Module
[
{deleteMissing,selectByAge},(*Helperfunctions:*)deleteMissing[data_]:=Select[data,FreeQ[#,Missing[___]]&];selectByAge[data_,interval_]:=Select[data,Between[#["age"],interval]&];(*Mainfunction:*)Histogram[selectByAge[deleteMissing[data],{minAge,maxAge}][[All,"age"]],{1},PlotLabel->StringForm["Distribution of passengers on the Titanic (aged `1` to `2`)",minAge,maxAge],Frame->True,FrameLabel->{"Age","Frequency"},ImageSize->500]]
];plotTitanicData[{0,20}]
Manipulate[plotTitanicData[minMax],{{minMax,100,"MinMax"},0,100,1},ControlType->IntervalSlider]
Block
Block
Block uses dynamic scoping. It sets up a miniature “global” environment in which the values of symbols can be temporarily reassigned. It is particularly useful for reassigning built-in constants.
Find the time in a different time zone:
Create a function that makes an engineering guesstimation for the volume of a planetary body by assuming that π = 3 and that the body is perfectly spherical:
Estimate the volume of Jupiter and compare it to the true result:
DynamicModule
DynamicModule
DynamicModule uses lexical scoping. It is what Manipulate uses behind the scenes, and as such is very useful for creating custom dynamic interfaces (sliders, buttons, etc.). As the name suggests, it is like Module, but for dynamic variables. (However, there are subtle differences—see the first Tech Note above for more details.)
Create a labelled slider with some dynamic elements and insert it into a dynamic interface:
Note the Dynamic wrapper in the first argument of labelledSlider. This serves two purposes: first, to enable the dynamic variable to be “scoped” by the DynamicModule; second, to make it clear to the user that the first argument is dynamic (there is no “DynamicQ” function in the Wolfram Language).
Here’s a version of the interface using Manipulate:
Automatic localisation
Automatic localisation
Other localisation
Other localisation
Several BeginX functions work with EndX functions to localise symbols. Compared to all of the other functions seen so far, these are somewhat unusual in that they do not use square brackets to enclose the things that are being localised.
f does not have any information without the full context:
Use BeginPackage and EndPackage to start and end a Wolfram Language package. These (together with Begin and End) are particularly useful for creating programs or codebases where symbol names are likely to conflict with those in the global context, or where definitions may need to be kept hidden from users. However, a full explanation goes beyond the scope of this course.
Useful Tips
Useful Tips
Syntax Information
Syntax Information
Function syntax refers to the allowed forms of a function—the patterns of arguments or options that are valid to use within it. If the allowed syntax has been defined for a function, invalid forms will be highlighted in red as the function is typed.
SyntaxInformation
SyntaxInformation
Specify that a function should take exactly one argument and zero options:
Optional arguments can be set with the same notation seen in Default earlier: an underscore followed by a full stop (_.).
Specify that a function should have at least one argument, but not more than two:
Specify that a function should take up to two arguments, plus some options:
SyntaxInformation may not always be able to distinguish between arguments and options:
CheckArguments
CheckArguments
CheckArguments allows arguments to be treated as options and vice versa:
Useful Tips
Useful Tips
Attributes
Attributes
Tutorial: Evaluation of Expressions
Rather than writing a general property into a function’s definition, some properties can be added as attributes:
Attributes gives the list of attributes associated with a function:
This list can be overwritten:
With the Orderless attribute, a function will sort its arguments (this is similar to OrderlessPatternSequence seen earlier):
Note that attributes generally apply to all arguments of a function (with some exceptions, like HoldFirst), so they should be considered carefully.
Consider the following function, which multiplies a vector by a scale factor. If the second argument is a list (of scale factors), it maps over it:
Attempting to recreate the function using the Listable attribute makes for shorter code:
However, the result is incorrect because the function now threads over both its arguments.
Useful Tips
Useful Tips
Optional: Speed and Efficiency
Optional: Speed and Efficiency
While a full lesson in how to write faster code goes beyond the scope of this course, here are some general tips taken from this Wolfram Blog post (some of which you have seen already).
1. Use decimals
1. Use decimals
Use reals instead of integers to give faster (but potentially less accurate) results.
Depending on the type of input, some functions may use entirely different methods to arrive at the same result.
2. Compile
2. Compile
3. Use built-in functions
3. Use built-in functions
Use built-in functions/algorithms where possible—they are almost always faster.
Flatten 10 million 2×2 lists into 1×4 lists:
4. Use an IDE / debugging tools
4. Use an IDE / debugging tools
For large projects, use an Integrated Development Environment (IDE) for easier code management. For precise navigation through buggy code, use Mathematica’s debugging tool (under Evaluation ▶ Debugger):
(This particular IDE shown above is IntelliJ IDEA, for which there is a Wolfram Language plugin available. Debugging was covered earlier.)
The following IDEs are supported:
5. Memoise
5. Memoise
Memoise functions to cache previous outputs.
(Memoisation was covered earlier.)
6. Parallelise
6. Parallelise
Run calculations in parallel with ParallelX functions:
7. Use Sow and Reap
7. Use Sow and Reap
(Sow and Reap work in a similar way to Throw and Catch.)
If you prefer the style of AppendTo, use associations instead of lists. This is not as fast as Sow and Reap, but appends in constant time, rather than time proportional to the length of the data:
8. Use Block or With
8. Use Block or With
Use Block or With instead of Module:
9. Use stricter pattern matching
9. Use stricter pattern matching
Use tighter patterns for faster searches—or avoid them altogether:
10. Try alternative methods
10. Try alternative methods
If one method is not getting fast enough results, try a different one:
Useful Tips
Useful Tips
Progress Monitoring
Progress Monitoring
Even with optimal code, a function may take some time to evaluate. During such an evaluation, it can be reassuring to see that something is happening—or better yet, to know how long it will take to finish.
Monitoring
Monitoring
Monitor allows you to temporarily display a dynamic object during an evaluation. A typical object to display is a ProgressIndicator, the duration of which can be known (“determinate”) or unknown (“indeterminate”).
Create a function that returns all of the prime numbers within a range, displaying a (determinate) dynamic progress bar while it is running:
Create a function that returns the birthday of a famous figure, displaying an indeterminate “loading necklace” while it is running:
Temporary printing
Temporary printing
PrintTemporary is essentially a more basic version of Monitor.
Create a function that temporarily prints the steps of an application’s build process (where, in this case, steps are mimicked with Pause):
Other monitoring options
Other monitoring options
Sow and reap the steps in order to plot them:
Useful Tips
Useful Tips
Extracting Information
Extracting Information
While full details about how a function works should be written up in documentation, key properties (definitions, options, etc.) can be extracted programmatically.
Function information
Function information
The quickest way to get information about a function is to use Information. For symbols, it has a convenient short form (??).
Under the hood, an Information object is an association with keys that can be extracted:
Extract the options of Dataset:
Information has another short form (?) for extracting usage messages.
Create a usage message for scaleVector (using the MessageName notation seen earlier) and extract it:
Definition will print a function’s attributes, default values, options and (unless the function is read-protected) definitions:
Object data
Object data
Information (in its long form) will also extract data from most objects:
Function names
Function names
Information can be used with asterisks (*) to find all the function names that match a particular form (where an asterisk represents zero or more characters).
Find all of the functions that contain the word “List” (case-sensitive):
Although Names does not format the result as nicely, it is more flexible because it allows string patterns.
Get only functions that contain “List” followed by an uppercase character (thus avoiding words like “Listen”):
Output forms
Output forms
Tech Note: Forms of Input and Output
Useful Tips
Useful Tips
Common Pitfalls
Common Pitfalls
In no particular order, here are some final tips and things to be aware of when writing a function.
Overloading
Overloading
When overloading, be careful about the ordering of function definitions. For custom functions with multiple definitions, the Wolfram Language will check for the more specific definitions before going to the generic definition. When the generality of definitions is not determined, the Wolfram Language will store and try definitions in the order that the definitions were created.
Include a catch-all definition.
Error catching
Error catching
Catch errors as early as possible.
If using branching functions, supply default values and ensure that all tests give Boolean results (True or False):
Use default argument/option values to ensure that a function always evaluates.
Function choice
Function choice
When modifying lists, use Sow and Reap instead of Append, AppendTo, etc.
If your test is a function, you should use Select.
If your test is a pattern, you should use Cases.
If you need to change/transform the elements while extracting them, you should use Cases.
If it can be a mix of a pattern and a test function, Cases is better.
Code writing
Code writing
If working on a large project, use an IDE to manage your code.
Generally, readable code is preferred over slightly faster/more compact code.
Format your code: use white space; use new lines; choose a spacing convention (tabs or spaces) and stick with it.
Comment your code!
Give your functions usage and error messages (and, if relevant, documentation).
Localise variables.
Use full symbol names instead of shorthand (e.g. Map instead of /@).
Summary
Summary
In this part of the course, you have covered:
Localisation
Syntax information
Attributes
Optional: speed and efficiency
Progress monitoring
Extracting information
Common pitfalls
Course Summary
Course Summary
Creating a basic function is easy; creating a function that is flexible, robust, intuitive and powerful is not. In this course, you have learned about:
Function structure: qualities of a good function, common practices, pure functions
Argument structure: implementation, restriction (pattern matching), optional arguments, default values, operator forms, subvalues
Option structure: implementation, restriction, duplication, filtering
Coding methods: overloading, recursion and iteration, memoisation, caching, upvalues
Error handling: flow control, messages, testing, debugging
Localisation, syntax information, attributes, progress monitoring, information extraction, speed and efficiency
Initialisation
Initialisation