​
Slide
1
of
14

Writing a Wolfram Language Function

THE BASICS OF FUNCTION STRUCTURE
​
​
Slide
2
of
14

Learning Objectives

Motivation


  • Learn the qualities of a good function
  • The Basics

    
  • Learn about standard function structure
  • 
  • Optional: learn about pure functions
  • Arguments

    
  • Add arguments to a function
  • 
  • Restrict a single argument in a function
  • 
  • Restrict multiple arguments in a function
  • 
  • Add optional arguments and default values
  • Summary

    ​
    ​
    Slide
    3
    of
    14

    Motivation

    ​
    Slide
    4
    of
    14

    Motivation

    Qualities of a Good Function

    Generally speaking, a “good” function is one that:
    
  • is robust to all input (i.e. it is difficult to break)
  • 
  • gives a clear output (i.e. it does what you expect it to do)
  • 
  • is flexible (i.e. it has the potential to be applied in contexts beyond its original scope)
  • 
  • has clear documentation (i.e. it can be used and understood by others)
  • In other words, when presented with a well-designed function, you should be able to read and understand its documentation, apply it in a variety of contexts and receive the results you expect.
    These are just guidelines, however; sometimes, for example, it is useful for a function to be deliberately inflexible, with few or no options. Functions of the form nameQ, for instance, often allow just one argument or no options:
    ​
    nameQ functions in the Wolfram Language
    Go to example
    ​
    ​
    Slide
    5
    of
    14

    The Basics

    ​
    Slide
    6
    of
    14

    The Basics

    Function Structure

    Standard structure

    The definition of a function typically takes the following form (mouse over the image for labels):

    Common practices

    For readability, it is usually best to:
    
  • use lowercaseCamelCase for the function name (and, to a lesser degree, its arguments)
  • 
  • use UppercaseCamelCase strings or symbols for any options
  • Other common conventions:
    
  • use nameQ for functions that will always evaluate to True or False (e.g. EvenQ). (These functions are known as predicate functions.)
  • 
  • use Nname for numerical functions (e.g. NSolve)
  • 
  • use $name for global variables (e.g. $Version)
  • Quick example

    Here is an example of a function with one argument that multiplies the argument by three:
    These lines add the option to take the modulus of the result:
    Here is the function in action:
    (The details of function construction will be covered later.)
    ​
    Slide
    7
    of
    14

    The Basics

    Optional: Pure Functions

    The standard structure of a function definition requires you to give the function a name, which is not always desirable. The alternative—a pure function—has the benefit that it is defined in the same place it is used, meaning that someone reading your code will not have to go hunting for a definition.

    Applications

    You might want to use a pure function if your function is:
    
  • very simple
  • 
  • only being used once
  • 
  • part of a larger function
  • Forms

    Pure functions come in a variety of forms, all of which use Function “under the hood”.
    Function
    Function is typically used in the form Function[parameters, body]:
    The parameters can be dropped in favour of slots (#):
    (body) &
    A pure function can be shortened further by replacing Function[body] with (body)&:
    Arguments can be referenced by their positions (# is equivalent to #1):
    When applied to associations, slots can be referenced by labels:
    f[slots] &
    Pure functions can even be used as arguments for other functions:
    ​

    Precedence

    When code is evaluated, operators are applied sequentially according to their precedence. This can be thought of as an extension to mathematical precedence, where, for example, multiplication is applied before addition:
    When using pure functions with an ampersand (&), it is usually best to include parentheses, both to make your intentions clear and to avoid errors.
    Here, the pattern test (?) binds more tightly than the function (&), so parentheses are required for the code to work properly:
    This can be checked by looking at the full form:
    ​
    Slide
    8
    of
    14

    Arguments

    ​
    Slide
    9
    of
    14

    Arguments

    Implementing Arguments

    Generally, arguments should be descriptive and lowerCamelCase. To add arguments to a function, put them (comma-separated) inside the square brackets:
    Note that there are underscores after the arguments on the left-hand side, but not on the right.
    A function can have no arguments at all. Even in this case, it is good practice to use square brackets to indicate that it is a function and not a variable:
    ​
    Slide
    10
    of
    14

    Arguments

    Restricting Arguments: Typical Approaches

    Tech Note: Patterns and Transformation Rules
    Restricting the arguments a function can take can make it more robust. It can also help someone to understand what the function is doing. Argument restriction is done with pattern matching, and there are a few common ways to do this.

    Head

    The simplest way to restrict an argument is to match a Head:

    Pattern test

    An alternative to matching a head is to use a PatternTest (?) with a predicate function:
    More complicated tests may require a pure function:

    Pattern

    A pattern can be assigned a label with Pattern (:):
    For simple patterns like this one, assigning a label is not really necessary. However, it can be very useful when patterns span multiple arguments (more on this later).

    Condition

    Another way to restrict an argument is to apply a Condition (/;) with a pattern test.
    This can be done inside the square brackets:
    …or outside the square brackets:
    For a condition with a complicated pattern test, applying it outside the square brackets usually makes the function easier to read. For a computationally expensive test, it may also make the function run slightly more quickly.
    ​
    ​
    Slide
    11
    of
    14

    Arguments

    Restricting Arguments: Multiple Arguments

    Rather than restricting one argument at a time, you can apply a pattern to several arguments at once.

    Pattern sequences

    Use BlankSequence (__) to match one or more expressions:
    Similarly, BlankNullSequence (___) will match zero or more expressions.
    Use PatternSequence to match a particular sequence of arguments:
    Use OrderlessPatternSequence to allow a sequence of arguments to be given in any order:

    Repeated patterns

    Use Repeated (..) to allow an argument to be repeated one or more times:
    Similarly, RepeatedNull (...) will allow zero or more arguments.
    Note that a repeated Blank (_) does not mean that all of the arguments have to be the same:
    To enforce this, you will need to name the expression being repeated:
    ​
    ​
    Slide
    12
    of
    14

    Arguments

    Optional Arguments and Default Values

    Having to insert all the arguments of a function every time it is used can be inconvenient. One solution is to make the arguments optional, replacing them with default values when the arguments are omitted.

    Optional

    Use Optional (:) to make an argument optional and give it a default value:
    As you may have noticed, the short form of Optional is the same as that for Pattern (a colon). However, it will usually be clear which is which from the context.
    When using Pattern and Optional together, the pattern must go first:
    The syntax arg_?test:value is not permitted. If you want to apply a pattern test and have a default value, you must use Pattern:
    ​

    Overloading

    Rather than specifying optional or default values, you can simply give a function multiple definitions. This is known as overloading (more on this later):
    ​
    Slide
    13
    of
    14

    Summary

    In this part of the course, you have covered:
    
  • Qualities of a good function
  • 
  • Standard function structure
  • 
  • Optional: pure functions
  • 
  • Implementing arguments
  • 
  • Restricting single arguments
  • 
  • Restricting multiple arguments
  • 
  • Optional arguments and default values
  • ​
    Slide
    14
    of
    14

    Initialisation