Estimated reading time: 3 minutes
In Julia, anonymous functions are functions that are defined without being assigned a name. They are sometimes also called lambda functions or function literals.
An anonymous function is created using the syntax args -> expr
, where args
is a comma-separated list of arguments and expr
is the expression that defines the body of the function. For example, the following is an anonymous function that takes two arguments and returns their sum:
julia> (x, y) -> x + y
#3 (generic function with 1 method)
How can anonymous capture variables?
Anonymous functions can capture variables from the enclosing scope, just like regular functions. For example:
julia> x = 10
10
julia> f = y -> x + y
#57 (generic function with 1 method)
julia> f(5)
15
Here, the anonymous function y -> x + y
captures the variable x
from the enclosing scope and adds it to its argument y
. When f(5)
is called, it returns 15
, which is the result of adding x
(which is 10
) to 5
.
How can anonymous functions be passed as arguments to other functions?
Anonymous functions can be passed as arguments to other functions or used in expressions just like named functions.
The most important bit to remember is to make “lt” = to the anonymous function, otherwise, it will throw up an error, and will not work!
The sort
function in Julia has several optional arguments that can be used to customize its behavior. Here’s an explanation of each of the arguments:
A::AbstractArray{T}
: This is the required argument that specifies the array to be sorted.T
specifies the element type of the array.dims
: This argument is used to specify the dimensions along which to sort a multidimensional array. For example,sort(A, dims=1)
sorts the columns ofA
separately.alg
: This argument is used to specify the sorting algorithm to use. The possible values areQuickSort
,MergeSort
,HeapSort
,InsertionSort
, andSelectionSort
.lt
: This argument is used to specify a custom “less than” function to use for sorting. The function should take two arguments and return a boolean indicating whether the first argument is less than the second.by
: This argument is used to specify a transformation to apply to each element of the array before sorting. For example,sort(A, by=abs)
sortsA
by the absolute values of its elements.rev
: This argument is used to specify whether to sort the array in reverse order.order
: This argument is used to specify the order in which to sort any ties. The possible values areForward
,Backward
, andRandom
.scratch
: This argument is used to specify an array to use as scratch space during sorting. This can improve performance for very large arrays.
For example, the following code uses an anonymous function to sort an array of integers in descending order:
julia> arr = [4, 2, 6, 1, 3, 5]
6-element Vector{Int64}:
4
2
6
1
3
5
julia> sort(arr, lt = (x, y) -> y < x)
6-element Vector{Int64}:
6
5
4
3
2
1