Introduction to Julia
James Fulton
Climate informatics researcher
Some functions modify inputs
Starting with the array:
x = [1,2,3]
push!(x, 4)
println(x)
[1, 2, 3, 4]
append!(x, [4,5,6])
println(x)
[1, 2, 3, 4, 5, 6]
pop!(x)
println(x)
[1, 2]
Starting with the array:
x = [3,1,2]
l = length(x)
println(x)
[3, 1, 2]
x_sorted = sort(x)
println(x)
[3, 1, 2]
x_type = typeof(x)
println(x)
[3, 1, 2]
Mutating functions change their inputs
pop!()
push!()
append!()
Non-mutating functions do not change their inputs
sort()
println()
typeof()
string()
length()
function modify_array!(x) x[1] = 0 end
# Try to mutate y y = [1,2,3,4,5] modify_array!(y)
# y has changed println(y)
[0, 2, 3, 4, 5]
function modify_array!(x) x = [0,2,3,4,5] end
# Try to mutate y y = [1,2,3,4,5] modify_array!(y)
# y has changed println(y)
[1, 2, 3, 4, 5]
function modify_array!(x) x[1] = 0 end
# Try to mutate y y = [1,2,3,4,5] modify_array!(y)
println(x)
ERROR: UndefVarError: x not defined
function modify_array!(x) x = [0,2,3,4,5] end
# Try to mutate y y = [1,2,3,4,5] modify_array!(y)
println(x)
ERROR: UndefVarError: x not defined
function setarray2zero!(x) x .= 0 end
y = [1,2,3,4,5] setarray2zero!(y)
println(y)
[0, 0, 0, 0, 0]
function modify_array!(x)
x .= x .- 1
end
y = [1,2,3,4,5]
modify_array!(y)
println(y)
[0, 1, 2, 3, 4]
function double(x)
return x*2
end
println(double(2)) # Works on integers
4
println(double(10.0)) # Works on floats
20.0
println(double("yo")) # Not on strings
ERROR: MethodError: ...
function double(x) return x*2 end
function double(x::String) return x*x end
println(double(2)) # Works on integers
4
println(double(10.0)) # Works on floats
20.0
println(double("yo")) # Works on strings
yoyo
function double(x) return x*2 end function double(x::String) return x*x end
function double(x::Bool) return x end
println(double(2)) # Works on integers
4
println(double(10.0)) # Works on floats
20.0
println(double("yo")) # Works on strings
yoyo
function double(x::String)
return x*x
end
function double(x::Bool)
return x
end
println(double(2)) # Not on integers
ERROR: MethodError: ...
println(double(10.0)) # Not on floats
ERROR: MethodError: ...
println(double("yo")) # Works on strings
yoyo
function double(x)
return x*2
end
Introduction to Julia