Multiple dispatch

Intermediate Julia

Anthony Markham

Quantitative Developer

Multiple dispatch recap

  • Multiple dispatch allows us to run a different method based on the type of argument passed into a function.
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
Intermediate Julia

Anonymous functions

  • Unlike typical functions, an anonymous function has no name.
  • Used to create quick functions which are discarded after use.
(x -> x^2 + 3)(2)
7
Intermediate Julia

Complex anonymous functions

  • 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
Intermediate Julia

Filtering DataFrames

  • 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

Let's practice!

Intermediate Julia

Preparing Video For Download...