Working with optional arguments

Sometimes, we do not want to hardcode any values in a function. The general solution is to extract the hardcoded values and work them into function arguments. In Julia, we can also provide default values for the arguments. When we have default values, then the arguments become optional.

To illustrate this concept, let's write a function that makes a bunch of asteroids:

# Make a bunch of asteroids
function make_asteroids(N::Int, pos_range = 0:200, size_range = 10:30)
pos_rand() = rand(pos_range)
sz_rand() = rand(size_range)
return [Widget("Asteroid #$i",
Position(pos_rand(), pos_rand()),
Size(sz_rand(), sz_rand()))
for i in 1:N]
end

The function takes an argument of N for the number of asteroids. It also accepts a position range, pos_range, and size_range, for creating randomly sized asteroids that are placed randomly on our game map. You may notice that we have also defined two single-line functions, pos_rand and sz_rand, directly inside the body of the make_asteroid function. These functions only exist within the scope of the function.

Let's try this out without specifying any value for pos_range or size_range:

But the fact that they are optional also allows us to provide custom values. For instance, we can place the asteroids closer to each other by specifying a much narrower range:

Where does the magic come from? If you hit the Tab key while entering the make_asteroid function from the REPL, you may notice that the single function definition ends up with three methods. 

What are functions and methods?

Functions are generic in Julia. This means that we can extend the purpose of a function by defining various methods that have the same name, but take different types of argument.

Hence, every function in Julia may be associated to one or more associated methods.

Internally, Julia automatically creates these three methods, one for each signature:

Another way to find the methods of a function is to just use the methods function that comes from the Julia Base package:

Of course, we can fully specify all arguments as such:

As you can see, it is quite convenient to provide default values for positional arguments. In the case that the default values are generally accepted, the calling function becomes simpler because it does not have to specify all arguments.

Something feels a little weird here, though—the code is becoming more difficult to read: make_asteroids(5, 100:5:200, 200:10:500). What does 5, 100:5:200, and 200:10:500 mean? These arguments look quite opaque, and the programmer may not remember what they mean without looking up the source code or the manual. There has to be a better way! Next, we will check how to solve this problem using keyword arguments.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.252.8