Lambda Expressions in Julia
Overview
In Julia, lambdas are defined as follows:
(x -> 3x^2 - 2x + 3)(1)
This corresponds to defining the anonymous function $\lambda : \mathbb{Z} \to \mathbb{Z}$, substituting $1$ into it, and obtaining the function value $4$. $$ \lambda : x \mapsto ( 3 x^{2} - 2 x + 3 ) \\ \lambda (1) = 4 $$ Indeed, lambda expressions themselves are not a Julia-specific feature but almost naturally supported, having been influenced by functional languages including MATLAB and Python. It is likely that learners interested in Julia have already had extensive experience using lambda expressions. However, for readers who may not know that ‘it’ they have been using was a lambda expression, or who still do not know its true value, we introduce two immediately applicable examples especially for them.
Example 1: Sorting lists by a different metric
Sorting lists can be quite straightforward with built-in functions, but one might want to sort based on priority across categories in multi-dimensional arrays or to sort original data by different criteria. In such cases, you can easily write the code by inserting the corresponding function as a lambda expression into the by option of the sort() function.
julia> # Example 1
julia> example = rand(-20:20,10)
10-element Array{Int64,1}:
3
8
19
-12
-20
9
-13
19
13
2
julia> sort(example, by=(x -> abs(x)))
10-element Array{Int64,1}:
2
3
8
9
-12
-13
13
19
19
-20
The above task represents sorting randomly selected integers from smallest to largest absolute values. It’s not impossible without lambda expressions, but it’s not as simple as it seems. By modifying the given lambda expression (x -> abs(x)), coders should be able to easily write the code they want.
Application of Example 1
Suppose a dictionary called value is created as follows.
In this case, code to sort by the size of dictionary values can be simply written using a lambda expression as sort(value,by=(x -> value[x]))
, and the result is as follows.
Example 2: Calculating frequency in a list
Languages that prioritize data like R even have built-in functions for it, but this frequency calculation is not as straightforward as it might seem. While not complex enough to be called an algorithm, it can be quite involving when actually implemented. This can also be easily solved using a lambda function!
julia> # Example 2
julia> example = rand(1:3,10); println(example)
[3, 1, 2, 2, 3, 2, 3, 1, 3, 3]
julia> uexample = sort(unique(example))
3-element Array{Int64,1}:
1
2
3
julia> counts = map(x->count(y->x==y,example),uexample)
3-element Array{Int64,1}:
2
3
5
The above task is about counting the frequencies of randomly chosen integers. The problem was solved simply by identifying the classes of data with unique() and then counting each element corresponding to those classes.
Environment
- OS: Windows
- julia: v1.5.0