Developing anonymous functions

Sometimes, we just want to create a simple function and pass it around without assigning it a name. This style of programming is actually fairly common in functional programming languages. We can illustrate its use with an example.

Suppose that we want to explode all of the asteroids. One way to do this is to define an explode function and pass it into the foreach function as follows:

function explode(x)
println(x, " exploded!")
end

function clean_up_galaxy(asteroids)
foreach(explode, asteroids)
end

The results look good:

We can achieve the same effect if we just pass an anonymous function into foreach:

function clean_up_galaxy(asteroids)
foreach(x -> println(x, " exploded!"), asteroids)
end

The syntax of the anonymous function contains the argument variables, followed by the thin arrow -> and the function body. In this case, we only have a single argument. If we have more arguments, then we can write them as a tuple that is enclosed in parentheses. An anonymous function can also be assigned to a variable and passed around. Let's say we want to explode the spaceships as well: 

function clean_up_galaxy(asteroids, spaceships)
ep = x -> println(x, " exploded!")
foreach(ep, asteroids)
foreach(ep, spaceships)
end

We can see that there are some advantages for using anonymous functions:

  • There is no need to come up with a function name and pollute the namespace of the module.
  • The anonymous function logic is available at the call site, so the code is easier to read.
  • The code is slightly more compact.

By now, we have gone over most of the pertinent details regarding how to define and use functions. The next topic, do-syntax, is closely related to anonymous functions. It is a great way to enhance code readability.

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

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