Writing a Wolfram Language Function
Writing a Wolfram Language Function
A WORKED EXAMPLE
This notebook shows an example function created from the ground up.
For full details of each step, see the lecture notebooks from the course.
For full details of each step, see the lecture notebooks from the course.
Motivation
Motivation
Qualities of a Good Function
Qualities of a Good Function
In this notebook, we are going to create an “image-styling” function. To get an idea of where we are heading, we will first demonstrate a ready-made version of the function on a test image:
testImage=ImageResize[ExampleData[{"TestImage","House"}],100]
Our image-styling function should take one image argument and one style argument. Accepted styles should include “Blur” (to blur the image), “Sharpen” (to sharpen the image) and “RGB” (to modify the image’s colour channels):
CreatingAFunction`Private`imageStyler[testImage,"Blur"]CreatingAFunction`Private`imageStyler[testImage,"Sharpen"]CreatingAFunction`Private`imageStyler[testImage,"RGB"]
Each style should have an option to modify its effect:
CreatingAFunction`Private`imageStyler[testImage,"Blur","Radius"->10]CreatingAFunction`Private`imageStyler[testImage,"Sharpen","Radius"->10]CreatingAFunction`Private`imageStyler[testImage,"RGB","RGBValues"->{3,2,1}]
The function should also take an independent greyscale option:
CreatingAFunction`Private`imageStyler[testImage,"Blur","GreyQ"->True]
CreatingAFunction`Private`imageStyler[testImage,"Blur",ImageSize->40]
The function should be robust to bad or no input:
CreatingAFunction`Private`imageStyler[badImage]CreatingAFunction`Private`imageStyler[testImage,"Blur",extraArgument]CreatingAFunction`Private`imageStyler[testImage,"Blur",badOption->value]CreatingAFunction`Private`imageStyler[testImage,"Blur","Radius"->badOptionValue]CreatingAFunction`Private`imageStyler[]
Finally, there should be a convenient way to extract information from the function:
Information[CreatingAFunction`Private`imageStyler]
The Basics
The Basics
Function Structure
Function Structure
First, we need to decide on a basic structure for the function:
ClearAll[imageStyler];imageStyler[image_,style_]:=Image[style[image]];
To apply the styling in the second argument, we will create some “helper” functions. Rather than putting these into the main function directly, we would like to use the strings “Blur”, “Sharpen” and “RGB”. One approach might be to use Switch:
ClearAll[imageStyler];imageStyler[image_,style_]:=Image[
Switch
[
style,"Blur",blurFunction[image],"Sharpen",sharpenFunction[image],"RGB",rgbFunction[image],_,image]
];Testing
Testing
The Switch statement applies each style function accordingly. However, without having defined them yet, they produce errors:
imageStyler[testImage,"Blur"]
imageStyler[testImage,"Sharpen"]
imageStyler[testImage,"RGB"]
imageStyler[testImage,badStyle]
Arguments
Arguments
Implementing Arguments
Implementing Arguments
To implement the image styles, we are going to define some helper functions. For blurring and sharpening, there already exist built-in functions that do the job:
Blur[testImage,10]
Sharpen[testImage,10]
For the “RGB” style, we need to create a custom function:
ClearAll[rgbStyle];rgbStyle[image_,{r_,g_,b_}]:=ColorCombine[{r,g,b}*ColorSeparate[image,"RGB"],"RGB"];
rgbStyle[testImage,{3,2,1}]
Let’s put these into our main function:
Testing
Testing
The styles work as intended, but there is no mechanism to modify their effects:
The function deals with some bad inputs well:
And others… not so well:
Arguments
Arguments
Restricting Arguments
Restricting Arguments
Our function should only accept an image and a string:
The RGB helper function should only accept an image and a list of three positive numbers. For convenience, we will make another small helper function to check that an expression is both numeric* and positive:
Testing
Testing
The function now deals with bad input slightly more gracefully:
However, leaving the function unevaluated is not ideal.
Arguments
Arguments
Optional Arguments and Default Values
Optional Arguments and Default Values
The style argument can be made optional by adding in a default value:
However, putting in a dummy value like this (to be dealt with by Switch) is a bit of a hack. One alternative is to modify the argument restriction to allow an Automatic style:
We can also give the RGB helper function some default values:
Testing
Testing
When given no explicit style, the main function now returns the original image:
Similarly, the RGB function will now accept one or two arguments:
Options
Options
Adding Options
Adding Options
There are three types of options we need to implement:
1
.Image options
2
.Style options
3
.A greyscale option
Image options
Image options
First, we’ll inherit the options from Image:
Style options
Style options
Now we can add the style options:
Greyscale option
Greyscale option
Finally, we can add a greyscale option. For this, we’ll introduce another helper function:
Testing
Testing
The Image options work as intended:
However, the custom styles do not, because they are being fed into Image:
Options
Options
Duplicated Options
Duplicated Options
The options that are not part of Image can be deleted:
Testing
Testing
The style and greyscale options now work as intended:
However, there are no restrictions on bad options:
Options
Options
Filtering Options
Filtering Options
Rather than deleting options, it is better to filter them:
Options
Options
Restricting Options
Restricting Options
We need to deal with bad option names and bad option values.
Option names
Option names
Option values
Option values
We can add to the condition to deal with bad option values:
Testing
Testing
The function no longer produces errors when given bad option names:
Nor does it produce errors when the style or greyscale options are given bad values:
However, it still produces errors when given bad Image option values:
It would be difficult to deal with all the possible Image option values individually, so we will catch these later with a different approach.
Extending Capability
Extending Capability
Overloading
Overloading
Our function can be converted from a Switch statement to multiple overloaded definitions.
Main definition
Main definition
Style definitions
Style definitions
Testing
Testing
The function’s behaviour is unchanged. Correct input still produces the desired results:
Bad option names do not produce errors:
Nor do bad option values (excluding those given to Image options):
However, the code is very repetitive.
Extending Capability
Extending Capability
Recursion and Iteration
Recursion and Iteration
The definitions can be reduced significantly with recursion. We can also add in more Automatic option values.
Main definition
Main definition
Style definitions
Style definitions
Testing
Testing
The function’s behaviour is largely unchanged. However, it now accepts more Automatic option values:
Extending Capability
Extending Capability
Upvalues
Upvalues
Testing
Testing
Error Handling
Error Handling
Flow Control: Exiting on Failures
Flow Control: Exiting on Failures
Earlier, we excluded Image errors from our restriction of option values. We can deal with these using ConfirmQuiet and Enclose:
Testing
Testing
The function no longer fails to evaluate when given bad Image option values*:
However, by returning the original image, there is no indication that a bad value was given. It would be better to print an error message along with the image.
*Unfortunately, due to an Image bug, certain options allow bad values to slip through:
*Unfortunately, due to an Image bug, certain options allow bad values to slip through:
There are ways to detect such front end rendering issues, but they go beyond the scope of this course.
Error Handling
Error Handling
Messages
Messages
Until now, whenever the function has been given bad input, it has either returned unevaluated or without an error message—neither of which is desirable.
Message list
Message list
For every error we want to catch—bad images, bad styles, bad options, etc.—we need an error message:
Overloading
Overloading
With more overloading, we can introduce specific error messages for specific forms of bad input.
Main definition
Bad input
Note all of the different conditions used to catch each type of bad input.
Testing
Testing
The function now deals with bad input gracefully, returning the original image (along with an error message) where possible:
In the cases where the original image is returned, the function can be used inside other functions with confidence:
Extra Tips
Extra Tips
Localisation
Localisation
In our quest to create an image-styling function, we have created a number of helper functions. Ideally, these should be localised so that they can only be accessed by the image-styling function itself.
However, for a function with a definition as large as ours, it would be clearer to use a package containing a local context. This is exactly what was done for the pre-made image-styling function:
Testing
Testing
The function can then be called using its full context path:
Extra Tips
Extra Tips
Extracting Information
Extracting Information
Let’s add a usage message:
Let’s also update the Information upvalue to include the usage message and descriptions for all of the options:
Testing
Testing
The function’s usage message can now be extracted:
It is now easier than ever to find out how to use the function:
Complete Function
Complete Function
Full Definition
Full Definition
The full definition of our image-styling function (identical to the pre-made function seen earlier) is given below. A few minor modifications have been made (in keeping with the ideas used in this course), such as converting the greyScale function from a branching function to an overloaded function.
Tests
Tests
Test the finished function:
Initialisation
Initialisation