Intermediate Julia
Anthony Markham
Quantitative Developer
function add_values(x, y)
x + y
end
add_values(1, 2) # 3
add_values("A", "B")
ERROR: MethodError: no method matching +(::String, ::String)
function add_values(x::String, y::String)
x * y
end
add_values("A", "B") # AB
(x -> x^2 + 3)(2)
7
Anonymous functions can have applications outside of simple function evaluation.
map() will apply each value in a collection to a function.
map(x -> 2*x + x^2 + 1, [1, 2, 3])
3-element Vector{Int64}:
4 9 16
map((x, y) -> 2*x + x^2 + 1 + y, [1, 2, 3], [1, 1, 1])
3-element Vector{Int64}:
5 10 17
The filter
function can be used to filter data structures with conditions.
We can use an anonymous function with filter
which helps us filter for a certain value.
filter!("Date" => n -> n == "21/01/2022", stock_data)
Row | Date Open High Low Close Adj Close Volume
| String15 Float64 Float64 Float64 Float64? Float64 Int64
<----|-----------------------------------------------------------------------
1 | 21/01/2022 164.42 166.33 162.3 162.41 161.473 122848900
Intermediate Julia