Learn Julia in half of an hour


Due to the similarity between Julia and {Python|MATLAB|R}, both in terms of syntax and design pattern, it is possible to bootstrap within less than 30 minutes and be able to understand vast majority of code. (Also thanks to Julia not use Class based OOP).

Inspired by a Rust tutorial.

x = 137 # create/assign a variable
137

Variables do have types:

typeof(x)
Int64

and you can re-bind the variable to a different value (even of a different type):

x = x + 2 # x is 139 after this line
x += 2 # x is now 141

x = 137.1 # x is 137.1, a Float64 now
137.1

Math works as you'd expect:

3/5
0.6

Rational number is a built-in type:

3//5
3//5

You can throw away un-used value by _:

_ = get_something() # value returned by function is lost

# also useful if you don't need the variable in the loop body
for _ in 1:10 
    ...
end

Tuple is a built-in type:

pair = ('c', 3)

# Julia is 1-indexed, by default
pair[1] # 'c'
pair[2] # 3
3

There are other ways to index a ordered collection:

# multiple comparison can be chained
pair[1] == pair[begin] == first(pair) # true
pair[2] == pair[end] == last(pair) # true

You can unpack a collection:

x, y = pair
# x is 'c', and y is 3

Functions are defined in this way:

function greet()
    println("hello")
end
greet (generic function with 1 method)

Indentation doesn't matter and you can also do this as 1-liner:

greet() = println("hello")

You can optionally specify the return type of a function, though compiler usually figures it out anyways and doing so may unnecessarily reduce flexibility

unfair_dice()::Int64 = 6
function sayhi(who::String = "world")
    println("hello, " who)
end

function sayhi(who::T) where T <: AbstractString
    println("hello, " who)
end

function Base.print(who::T) where T
    println("hello, " who)
end

saybye(who::String = "world") = println("goodbye, ", who)
saybye(who::T) where T <: AbstractString = println("goodbye, ", who)
Base.print(who::T) where T = println("goodbye, ", who)