Julia Language Anonymous functions


Example

Arrow syntax

Anonymous functions can be created using the -> syntax. This is useful for passing functions to higher-order functions, such as the map function. The below function computes the square of each number in an array A.

squareall(A) = map(x -> x ^ 2, A)

An example of using this function:

julia> squareall(1:10)
10-element Array{Int64,1}:
   1
   4
   9
  16
  25
  36
  49
  64
  81
 100

Multiline syntax

Multiline anonymous functions can be created using function syntax. For instance, the following example computes the factorials of the first n numbers, but using an anonymous function instead of the built in factorial.

julia> map(function (n)
               product = one(n)
               for i in 1:n
                   product *= i
               end
               product
           end, 1:10)
10-element Array{Int64,1}:
       1
       2
       6
      24
     120
     720
    5040
   40320
  362880
 3628800

Do block syntax

Because it is so common to pass an anonymous function as the first argument to a function, there is a do block syntax. The syntax

map(A) do x
    x ^ 2
end

is equivalent to

map(x -> x ^ 2, A)

but the former can be more clear in many situations, especially if a lot of computation is being done in the anonymous function. do block syntax is especially useful for file input and output for resource management reasons.