Writing a Wolfram Language Function
Writing a Wolfram Language Function
EXTENDING CAPABILITY
Learning Objectives
Learning Objectives
Extending Capability
Extending Capability
Overload a function with multiple definitions
Make a function recursive or iterative
Use memoisation to speed up a function
Cache values to speed up a function
Use upvalues to give a function different properties in different contexts
Optional: learn about operators and subvalues
Summary
Summary
Extending Capability
Extending Capability
Extending Capability
Extending Capability
Overloading
Overloading
Overloading a function simply means giving it multiple definitions for different types of input.
Standard usage
Standard usage
Round and square a number whether it is given as an integer, a fraction, a decimal or a string:
ClearAll[square];square[integer_Integer]:=integer^2;square[fraction_Rational]:=Round[Divide@@NumeratorDenominator[fraction]]^2;square[decimal_Real]:=Round[decimal]^2;square[string_String]:=Round[Interpreter["SemanticNumber"][string]]^2;square[23]square[69/3]square[23.4]square["twenty three point four"]
ClearAll[evenOddFun]evenOddFun[number_?EvenQ]:=number/2;evenOddFun[number_?OddQ]:=3*number+1;evenOddFun[4]evenOddFun[5]
ClearAll[myAbs]myAbs[number_/;number>=0]:=number;myAbs[number_/;number<0]:=-number;myAbs[123]myAbs[-123]
Dependent arguments
Dependent arguments
With the usual function syntax, the default value of one argument cannot be dependent on another argument:
ClearAll[f];f[
x_
:1,y_:
x
]:={x,y};f[1]However, this behaviour can be mimicked with overloading.
Create a function where the default value of the second argument equals the first argument:
ClearAll[f];f[x_,y_]:={x,y};f[x_:1]:={x,x};f[]f[a]f[a,b]
Optional: Alternative solutions
Dependent option values
Dependent option values
The same principle can be applied to option values.
Create a function that puts a frame around a piece of text, where the rounding radius scales with the size of the frame margins:
ClearAll[frameText];Options[frameText]=DeleteDuplicatesBy[Join[{FrameMargins->10},(*ReplacethedefaultvalueofFrameMargins–Automatic–withanumericvalue*)Options[Framed]],First];(*WhennoexplicitRoundingRadiusisgiven,scaleitwiththeFrameMargin:*)frameText[text_String,options:OptionsPattern[]]
/;
FreeQ[{options},RoundingRadius]
:=Framed[Text[text],RoundingRadius->OptionValue[FrameMargins]/2
,options];frameText[text_String,options:OptionsPattern[]]:=Framed[Text[text],options];frameText["text"]frameText["text",FrameMargins->50]frameText["text",RoundingRadius->10]frameText["text",FrameMargins->50,RoundingRadius->10]
Catch-alls and zero arguments
Catch-alls and zero arguments
Overloading is especially useful for creating a “catch-all”: a definition designed to handle any input types previously unaccounted for.
The square function defined earlier will not evaluate if the input is not an integer, fraction, decimal or string:
Add a catch-all case:
Additionally, rather than making every argument optional, overloading can be used to define a special zero-argument case:
The function will now handle all edge cases:
Extending Capability
Extending Capability
Recursion and Iteration
Recursion and Iteration
Recursive and iterative functions (often known as “self-referential” and “looping” functions, respectively) are useful for tasks that can be broken down into smaller subtasks. (Click here for an example of self-reference.)
Recursion
Recursion
Create a function to get the names and sizes of all files within a directory, regardless of its structure:
Apply the function to an example directory:
Iteration: Looping constructs
Iteration: Looping constructs
Guide: Looping Constructs
Looping constructs employ what might be called “standard” iteration. They are useful for carrying out tasks a predetermined number of times or until a test fails to give True. Often different looping constructs can be used to perform the same task.
Create the same function with Do:
Note that Do, unlike Table, does not return an output—hence the more verbose code in this case.
Note that Do and Table localise their variables, but For and While do not (more on localisation later).
Iteration: Functional iteration
Iteration: Functional iteration
Guide: Functional Iteration
Functional iteration is very similar to recursion and is carried out in much the same way: with overloading.
Create a function to find the remainder after dividing one number by another:
Functional iteration is easy to confuse with recursion. In functional iteration, the function being iterated must be the head of the expression on the right-hand side of the definition:
In recursion, the function can appear anywhere on the right-hand side:
For functional iteration (but not looping constructs), the number of levels of iteration is limited by the value of $IterationLimit:
Extending Capability
Extending Capability
Memoisation
Memoisation
Memoisation is a method of caching values to make iterative or recursive functions run more quickly.
Consider the recursive Fibonacci function created earlier:
Incorporating memoisation makes the function much faster:
Extending Capability
Extending Capability
Caching
Caching
For further evaluations of the same expression, only the result from the first evaluation is given:
This can be utilised in a similar way to memoisation:
However, once again, the values have to be stored somewhere:
Extending Capability
Extending Capability
Upvalues
Upvalues
When a function is defined in the standard way, its definition is stored as a downvalue:
Sometimes it can be useful\b for a function to behave differently when it is used in a particular context. TagSetDelayed (/:) can set up special definitions for a function when it is being used inside an expression. These definitions are then stored as upvalues:
Standard usage
Standard usage
Rule systems
A good use of upvalues is for creating a “rule system” for a particular type of object.
Define your own version of logarithmic addition for positive numbers:
Note that log[a*b] does not evaluate any further because log does not have any downvalues. If it did, they would disrupt the TagSetDelayed definition.
Databases
Another common use of upvalues is in setting up a “database” of properties for an object.
(Information will be covered in more detail later.)
Create an arithmetic object from which various properties can be extracted:
Upvalues vs downvalues
Upvalues vs downvalues
However, since Plus is a built-in function—and fundamental to many other built-in functions!—changing its definition would be a very bad idea. As a general rule of thumb, it is better to create upvalues for less common functions than to create downvalues for more common ones.
Extending Capability
Extending Capability
Optional: Operator Forms and Subvalues
Optional: Operator Forms and Subvalues
Operator forms and (object) subvalues have similar syntax, but serve different purposes.
Operator forms
Operator forms
While functions are often applied to expressions by “wrapping around” them, an operator form of a function (if it exists) allows it to be applied as a Prefix. In this respect, an operator form acts a bit like a pure function.
Select, for example, has an operator form. Use Select on a list in the “regular” way, as an operator and as a pure function:
Defining an operator form of a function is very similar to defining a function in the usual way—there are just more square brackets involved:
When a regular function is defined, the definition on the right-hand side of the SetDelayed symbol (:=) is stored as a downvalue for the function. When an operator form is defined, the definition is stored as a subvalue:
Operators can go as “deep” as you like:
Subvalues (of objects)
Subvalues (of objects)
Sometimes, when the output of a function is large or cumbersome, it can be convenient to display it as an “object”:
This necessitates a mechanism to extract the object’s inner data. A typical function for doing this is Normal:
However, the problem with this is that it extracts all of the data at once—potentially thousands or millions of data points. Defining subvalues for an object provides a way around this, allowing small snippets of data to be extracted independently.
Notice that the syntax for object subvalues is very similar to that of operator forms; the same can be said for how they are defined.
Create a function that produces an “arithmetic object”, then define subvalues for that object to extract its properties:
Note that arithmeticObject[x, y] on its own does not evaluate any further. This is because arithmeticObject does not have any downvalues. If it did, they would disrupt the subvalue definitions—but evaluation order is going beyond the scope of this course.
Summary
Summary
In this part of the course, you have covered:
Overloading
Recursion and iteration
Memoisation
Caching
Upvalues
Optional: operators and subvalues
Self-Reference
Self-Reference
Click here for an example of self-reference.
Initialisation
Initialisation