function mysum(a) s = zero(eltype(a)) for x in a s += x end return s end a = rand(10^7) mysum(a) mysum(a) ≈ sum(a) using BenchmarkTools @btime sum($a) @btime mysum($a) z = rand(Complex{Float64}, length(a)); @btime mysum($z) s = Set([2, 17, 6 , 24]) typeof(s) 2 in s, 13 in s mysum(s) f(x) = x + 1 f(3) # x is an integer (technically, a 64-bit integer) f(3.1) # x is a floating-point value (Float64) f([1,2,3]) # x is an array of integers f("hello") @code_llvm f(1) @code_native f(1) g(x) = f(x) * 2 g(1) @code_llvm g(1) h(x) = g(x) * 2 @code_llvm h(1) fib(n::Integer) = n < 3 ? 1 : fib(n-1) + fib(n-2) [fib(n) for n = 1:10] fib.(1:10) @code_warntype fib(1) fib(3.7) function myfact(n::Integer) n < 0 && throw(DomainError("n must be positive")) return n < 2 ? one(n) : n * myfact(n-1) end myfact(10) myfact(BigInt(100)) myfact(3.7) using SpecialFunctions myfact(x::Number) = gamma(x+1) myfact(5.0) myfact(-0.5)^2 methods(myfact) methods(+) @which (+)(3,4) f(x,y) = 3 f(x::Integer,y::Integer) = 4 f(x::Number,y::Integer) = 5 f(3,4), f(3.5,4), f(4,3.5) "3" * "7" "3" + "7" Base.:+(a::AbstractString, b::AbstractString) = a * " + " * b "3" + "7" sum(["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]) sqrt(4) sqrt(-1) sqrt(-1 + 0im) mysqrt(x::Complex) = sqrt(x) mysqrt(x::Real) = x < 0 ? sqrt(complex(x)) : sqrt(x) mysqrt(2) mysqrt(-2) mysqrt(-2+0im) slowfun(x) = mysqrt(x) + 1 @code_warntype slowfun(2) mutable struct Point1 x y end Base.:+(p::Point1, q::Point1) = Point1(p.x + q.x, p.y + q.y) Base.zero(::Type{Point1}) = Point1(0,0) Point1(3,4) Point1(3,4) + Point1(5,6) Point1(3.7, 4+5im) Point1("x", [3,4,5]) p = Point1(3,4) p.x = 7 p P = [p,p,p] p.y = 8 P a1 = Point1.(a, a) @btime sum($a1) @btime mysum($a1) struct Point2 x::Float64 y::Float64 end Base.:+(p::Point2, q::Point2) = Point2(p.x + q.x, p.y + q.y) Base.zero(::Type{Point2}) = Point2(0.0,0.0) Point2(3,4) Point2(3,4) + Point2(5,6) p = Point2(3,4) P = [p,p,p] p.x = 6 # gives an error since p is immutable a2 = Point2.(a,a) @btime sum($a2) struct Point3{T<:Real} x::T y::T end Base.:+(p::Point3, q::Point3) = Point3(p.x + q.x, p.y + q.y) Base.zero(::Type{Point3{T}}) where {T} = Point3(zero(T),zero(T)) Point3(3,4) Point3(3,4) + Point3(5.6, 7.8) a3 = Point3.(a,a) @btime sum($a3) @btime mysum($a3)