using InstantiateFromURL github_project("QuantEcon/quantecon-notebooks-julia", version = "0.1.0") using LinearAlgebra, Statistics, Compat +(1, 1) x, y = 1.0, 1.0 @which +(x, y) x, y = 1, 1 @which +(x, y) x, y = 1.0 + 1.0im, 1.0 + 1.0im @which +(x, y) import Base: + # enables adding methods to the + function +(x::Integer, y::String) = x + parse(Int, y) @show +(100, "100") @show 100 + "100"; # equivalent supertype(Float64) supertype(ComplexF32) @show (typeof(100.0) <: Integer) == false 100.0 + "100" function q(x) # or q(x::Any) println("Default (Any) method invoked") end function q(x::Number) println("Number method invoked") end function q(x::Integer) println("Integer method invoked") end q(3) q(3.0) q("foo") x = [1, 2, 3] f(x) = 2x @code_warntype f(x) f(x) = x > 0.0 ? x : nothing @code_warntype f(1) f(x) = x > 0.0 ? x : 0.0 @code_warntype f(1) f(x) = x > 0.0 ? x : 0 @code_warntype f(1.0) @show zero(2.3) @show zero(4) @show zero(2.0 + 3im) f(x) = x > 0.0 ? x : zero(x) @code_warntype f(1.0) function f(a, b) y = 2a + 8b return y end function f(a, b) y = (a + 8b)^2 return 7y end @code_native f(1, 2) @code_native f(1.0, 2.0) b = 1.0 function g(a) global b for i ∈ 1:1_000_000 tmp = a + b end end using BenchmarkTools @btime g(1.0) @code_native g(1.0) function g(a, b) for i ∈ 1:1_000_000 tmp = a + b end end @btime g(1.0, 1.0) @code_native g(1.0, 1.0) const b_const = 1.0 function g(a) global b_const for i ∈ 1:1_000_000 tmp = a + b_const end end struct Foo_generic a end struct Foo_abstract a::Real end struct Foo_concrete{T <: Real} a::T end fg = Foo_generic(1.0) fa = Foo_abstract(1.0) fc = Foo_concrete(1.0) typeof(fc) function f(foo) for i ∈ 1:1_000_000 tmp = i + foo.a end end @btime f($fg) @code_native f(fg) @btime f($fa) @btime f($fc) @code_native f(fc) function sum_float_array(x::AbstractVector{<:Number}) sum = 0.0 for i ∈ eachindex(x) sum += x[i] end return sum end x = range(0, 1, length = Int(1e6)) x = collect(x) typeof(x) @btime sum_float_array($x) function sum_array(x) sum = 0.0 for i ∈ eachindex(x) sum += x[i] end return sum end @btime sum_array($x) x = Any[ 1/i for i ∈ 1:1e6 ]; eltype(x) @btime sum_array($x)