🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Anonymous Functions

An anonymous function is a function with no name, written for a quick job in one place. The arrow -> separates its input from the work it does.

Map applies an unnamed function to each item

The anonymous function adds 1 to its input. Map runs it on each item of the small array.

println(map(x -> x + 1, [1, 2, 3]))

Each result lands in the same position

Here the anonymous function squares its input. Each squared value appears where its input stood.

println(map(x -> x * x, [2, 3, 4]))

An anonymous function can be stored

Saving the function in a variable gives it a handle. Calling that variable runs the function.

triple = x -> x * 3

println(triple(4))
println(triple(10))

Example

addten = x -> x + 10

println(map(x -> x * 2, [1, 2, 3]))
println(addten(5))
println(map(addten, [0, 1, 2]))

Key points

  • Anonymous: this kind of function has no name of its own.
  • Arrow: x -> expression reads the left side as the input and the right side as the result.
  • Map: the map function applies a function to each item and collects the results.
  • Array literal: values in square brackets, such as [1, 2, 3], form a small list of values.
  • Stored function: an anonymous function can be saved in a variable and called through that variable.

In this example, addten stores an anonymous function that adds 10. Map first doubles each item of the array with a function written in place. Last, map runs the stored addten on each item and prints the new array.

Note

Give a function a name when the same work is needed in many places.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does println(map(x -> x - 1, [3, 4, 5])) print?