Splatting arguments 

Slurping is very useful in its own right, but the triple-dot notation actually has a second usage. At the call site, when a variable is followed by three periods, the variable will be automatically assigned as multiple function arguments. This feature is known as splatting. In fact, this mechanism is very similar to slurping, except that it is doing the opposite action. We will take a look at an example.

Let's say that we have written a function to arrange a couple of spaceships in a specific formation:

# Special arrangement before attacks
function triangular_formation!(s1::Widget, s2::Widget, s3::Widget)
x_offset = 30
y_offset = 50
s2.position.x = s1.position.x - x_offset
s3.position.x = s1.position.x + x_offset
s2.position.y = s3.position.y = s1.position.y - y_offset
(s1, s2, s3)
end

We have also constructed a couple of spaceships ahead of a space war:

We can now call the triangular_formation! function using the splatting technique, which involves appending three periods after the function argument:

In this case, the three elements inside the spaceships vector are distributed to the three arguments as the triangular_formation! function expects. 

Splatting can technically work with any collection type—vector and tuple. It should work as long as the variable being splatted supports the general iteration interface. 
In addition, you may wonder what happens when the number of elements in the variable does not equal the number of arguments as defined in the function.

You are encouraged to check this behavior out as an exercise.

Splatting is a good way to build up function arguments and then pass them into the function directly without having to split them up into separate arguments. It is therefore quite convenient.

Next, we will discuss how functions can be passed around to provide higher-order programming facilities.

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

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