多重分派

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
Julia 中级

匿名函数

  • 与普通函数不同,匿名函数没有名称。
  • 用于快速创建一次性函数。
(x -> x^2 + 3)(2)
7
Julia 中级

更复杂的匿名函数

  • 匿名函数不止用于简单求值。

  • map() 会将集合中的每个值传入函数。

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
Julia 中级

筛选 DataFrame

  • 使用 filter 按条件筛选数据结构。

  • 可在 filter 中用匿名函数筛选特定值。

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
Julia 中级

开始练习!

Julia 中级

Preparing Video For Download...