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.
​
​
Slide
1
of
18

Motivation

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]
As well as these custom options, it should inherit all of the options from Image:
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]
​
​
Slide
2
of
18

The Basics

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

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]
​
​
Slide
3
of
18

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

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:
​
Slide
4
of
18

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:
​
*NumericQ and NumberQ are not quite the same. NumericQ checks whether an expression represents a number, whereas NumberQ only checks whether the expression has a number-related Head.

Testing

The function now deals with bad input slightly more gracefully:
However, leaving the function unevaluated is not ideal.
​
Slide
5
of
18

Arguments

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

When given no explicit style, the main function now returns the original image:
Similarly, the RGB function will now accept one or two arguments:
​
Slide
6
of
18

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

First, we’ll inherit the options from Image:

Style options

Now we can add the style options:

Greyscale option

Finally, we can add a greyscale option. For this, we’ll introduce another helper function:

Testing

The Image options work as intended:
However, the custom styles do not, because they are being fed into Image:
​
Slide
7
of
18

Options

Duplicated Options

The options that are not part of Image can be deleted:

Testing

The style and greyscale options now work as intended:
However, there are no restrictions on bad options:
​
Slide
8
of
18

Options

Filtering Options

Rather than deleting options, it is better to filter them:
​
Slide
9
of
18

Options

Restricting Options

We need to deal with bad option names and bad option values.

Option names

We can add a Condition to deal with bad option names:

Option values

We can add to the condition to deal with bad option values:

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.
​
Slide
10
of
18

Extending Capability

Overloading

Our function can be converted from a Switch statement to multiple overloaded definitions.

Main definition

Style definitions

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.
​
Slide
11
of
18

Extending Capability

Recursion and Iteration

The definitions can be reduced significantly with recursion. We can also add in more Automatic option values.

Main definition

Style definitions

Testing

The function’s behaviour is largely unchanged. However, it now accepts more Automatic option values:
​
Slide
12
of
18

Extending Capability

Upvalues

Let’s add an upvalue containing a Dataset of default option values:

Testing

Details about the function can now be extracted with Information:
​
Slide
13
of
18

Error Handling

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

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:
There are ways to detect such front end rendering issues, but they go beyond the scope of this course.
​
Slide
14
of
18

Error Handling

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

For every error we want to catch—bad images, bad styles, bad options, etc.—we need an error message:

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

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:
​
Slide
15
of
18

Extra Tips

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.
One approach might be to put everything inside a Module:
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

The package containing the pre-made image-styling function can be loaded with Get:
The function can then be called using its full context path:
​
Slide
16
of
18

Extra Tips

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

The function’s usage message can now be extracted:
It is now easier than ever to find out how to use the function:
The underlying association can be obtained with Normal:
​
Slide
17
of
18

Complete Function

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

Test the finished function:
​
Slide
18
of
18

Initialisation