Go Inspired Tour of Julia

A quick tour of the basic features of the Julia programming language.

Image for post
Image for post
Running some Julia code in the Julia REPL (Read Evalulate Program Loop) enironment.

Hello World

println("Hello, 世界")

Functions

function add(x::Int, y::Int)
return x + y
end

println(add(42, 13))

Variables

x, y, z = 1, 2, 3
julia, python, java = true, false, "no!"

println(join([x, y, z, julia, python, java], ' '))
1 2 3 true false no!
x = 10
function foo()
x = 4

global y
y = 5
return x
end
julia> foo()
4
julia> x
10
julia> y
5

For Loop

sum = 0
for i in 0:9
sum += i
end
println(sum)

While Loop

sum = 1
while sum < 1000
sum += sum
end
println(sum)

If Statement

function mysqrt(x::Float64)
if x < 0
string(mysqrt(-x), "i")
else
string(sqrt(x))
end
end

println(mysqrt(2.0), " ", mysqrt(-4.0))

Structs

struct FooBar
spam::Char
foo::Int64
bar::String
end
a = FooBar('B', 12, "Days")
julia> a.spam
'B': ASCII/Unicode U+0042 (category Lu: Letter, uppercase)
julia> getfield(a, :foo)
12
julia> getfield(a, 3)
"Days"

Dictionary

struct Vertex
lat::Float64
long::Float64
end

m = Dict{String, Vertex}()
m["Bell Labs"] = Vertex(40.68433, -74.39967)
println(m["Bell Labs"])
m = Dict("Bell Labs" => Vertex(40.68433, -74.39967))

Arrays

p = [2, 3, 5, 7, 11, 13]
println("p == ", p)
for i = 1:length(p)
println("p[$i] == $(p[i])")
end
p = UInt8[2, 3, 5, 7, 11, 13]
julia> m = [1 2 3; 3 4 5]
2×3 Array{Int64,2}:
1 2 3
3 4 5

Slices

a = [2, 4, 6, 8, 10]
println(a)
println(a[1:2])
println(a[1:4])
println(a[3:3])
julia> a[[3,2]]
2-element Array{Int64,1}:
6
4

Function Values

hypot = (x, y) -> sqrt(x^2 + y^2)
println(hypot(3, 4))

Function Closures

function adder()
sum = 0
x -> sum += x
end

pos, neg = adder(), adder()
for i = 0:9
println(pos(i), " ", neg(-2*i))
end

Methods

struct Vertex
x::Float64
y::Float64
end

function abs(v::Vertex)
sqrt(v.x^2 + v.y^2)
end

function abs(f::Float64)
f < 0 ? -f : f
end

v = Vertex(3, 4)
println(abs(v))

v = -sqrt(2)
println(abs(v))

Enumerations

@enum Weekday monday tuesday wednesday thursday friday

function describe(day::Weekday)
if day == monday
"Moon day"
elseif day == tuesday
"Tyr's day"
else
string(day)
end
end

println(describe(monday))
println(describe(tuesday))
println(describe(wednesday))

Where to Go From Here

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store