​
Slide
1
of
13

Writing a Wolfram Language Function

USEFUL TIPS
​
​
Slide
2
of
13

Learning Objectives

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

    Course Summary

    ​
    ​
    Slide
    3
    of
    13

    Useful Tips

    ​
    Slide
    4
    of
    13

    Useful Tips

    Localisation

    Tech Note: Modularity and the Naming of Things​
    Guide: Scoping Constructs
    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

    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}]},​​​​ListPlot​​initialData,​​PlotRange->{{0,noOfPoints},MinMax[initialData]+{-1,1}},​​PlotLegends->Grid​​{​​{"Mean",Mean[initialData]},​​{"Range",First[Differences[MinMax[initialData]]]}​​},​​
    Grid options
    ​​,​​
    Plot options
    ​​​​
    
    ;​​​​plotData[200]

    Module

    Tech Note: Modules and Local Variables​
    Tech Note: How Modules Work
    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

    Tech Note: Blocks and Local Variables​
    Tech Note: Blocks Compared with Modules
    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

    Tech Note: Module versus DynamicModule​
    Tech Note: Introduction to Dynamic
    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

    Other localisation

    Throw/Catch, Confirm/Enclose and Quiet/Check do some localisation behind the scenes to ensure a controlled transfer of information.
    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.
    Use Begin and End to create a function in the context MyContext`:
    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.
    ​
    Slide
    5
    of
    13

    Useful Tips

    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

    A function’s syntax can be set with 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:
    Syntax information can be cleared with Unset (=.):
    ​

    CheckArguments

    A function’s syntax can be checked (without evaluating it) with CheckArguments:
    CheckArguments allows arguments to be treated as options and vice versa:
    ​
    Slide
    6
    of
    13

    Useful Tips

    Attributes

    Tutorial: Evaluation of Expressions
    Rather than writing a general property into a function’s definition, some properties can be added as attributes:
    (The full list can also be found here.)
    Attributes gives the list of attributes associated with a function:
    This list can be overwritten:
    With the Listable attribute, a function will “thread over” a list argument automatically:
    Use SetAttributes to add to the list of existing attributes without overwriting it:
    With the Orderless attribute, a function will sort its arguments (this is similar to OrderlessPatternSequence seen earlier):
    Clear one or more attributes of a function with ClearAttributes:
    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.
    ​
    Slide
    7
    of
    13

    Useful Tips

    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

    Use reals instead of integers to give faster (but potentially less accurate) results.
    Calculate the determinant of a 100×100 matrix:
    Depending on the type of input, some functions may use entirely different methods to arrive at the same result.
    With real input, Solve will use numerical methods:

    2. Compile

    Use Compile to convert Wolfram Language code into faster machine code.

    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

    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

    Memoise functions to cache previous outputs.
    ​
    (Memoisation was covered earlier.)

    6. Parallelise

    Run calculations in parallel with ParallelX functions:

    7. Use Sow and Reap

    When working with lists, use Sow and Reap instead of Append/AppendTo or Prepend/PrependTo:
    (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

    Use Block or With instead of Module:

    9. Use stricter pattern matching

    Use tighter patterns for faster searches—or avoid them altogether:

    10. Try alternative methods

    If one method is not getting fast enough results, try a different one:

    ​

    ​
    Slide
    8
    of
    13

    Useful Tips

    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

    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

    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

    Some functions like StepMonitor and EvaluationMonitor have monitoring built in.
    Print the steps of FindRoot as it searches for a solution:
    Sow and reap the steps in order to plot them:
    ​
    ​
    Slide
    9
    of
    13

    Useful Tips

    Extracting Information

    Tech Note: Getting Information about Wolfram Language Objects
    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

    The quickest way to get information about a function is to use Information. For symbols, it has a convenient short form (??).
    Get information about Dataset:
    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:
    (FullDefinition will also give any dependent definitions, if they exist.)
    ​

    Object data

    Information (in its long form) will also extract data from most objects:
    As seen earlier, Normal can often be used to get data out of an object. Another trick is to replace the head of the object using Apply and List:

    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):
    Use Names to get a similar result:
    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

    Tech Note: Forms of Input and Output
    By default, expressions are output in StandardForm, but there are many other forms too:
    To get the underlying expression, you can use InputForm (or, for an even “deeper” look, FullForm):
    ​
    Slide
    10
    of
    13

    Useful Tips

    Common Pitfalls

    In no particular order, here are some final tips and things to be aware of when writing a function.

    Overloading

    
  • Use overloading rather than a branching function (If, Which, Switch, …).
  • 
  • 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

    
  • 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

    
  • Use Do, Table, etc. instead of For.
  • 
  • When modifying lists, use Sow and Reap instead of Append, AppendTo, etc.
  • 
  • Use Replace with a level specification instead of ReplaceAll:
  • 
  • Do not use Return.
  • 
  • Use Cases and Select properly:
  • 
  • 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

    
  • 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 /@).
  • 
  • Use parentheses for clarity (especially when pattern matching or writing a CompoundExpression).
  • ​
    Slide
    11
    of
    13

    Summary

    In this part of the course, you have covered:
    
  • Localisation
  • 
  • Syntax information
  • 
  • Attributes
  • 
  • Optional: speed and efficiency
  • 
  • Progress monitoring
  • 
  • Extracting information
  • 
  • Common pitfalls
  • ​
    Slide
    12
    of
    13

    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
  • ​

    ​
    Slide
    13
    of
    13

    Initialisation