Julia Quick Start

video
manual

Using package

In [1]:
using Printf
using Statistics

Dynamic data type

In [2]:
s  = 0
s = "dog"
println(s)
dog

Assert data type

In [3]:
function changeNum()
    x::Int8 = 10
    x = "Dog"
end

changeNum()
MethodError: Cannot `convert` an object of type String to an object of type Int8
Closest candidates are:
  convert(::Type{T}, !Matched::T) where T<:Number at number.jl:6
  convert(::Type{T}, !Matched::Number) where T<:Number at number.jl:7
  convert(::Type{T}, !Matched::Ptr) where T<:Integer at pointer.jl:23
  ...

Stacktrace:
 [1] changeNum() at ./In[3]:3
 [2] top-level scope at In[3]:6
 [3] include_string(::Function, ::Module, ::String, ::String) at ./loading.jl:1091

Cast type

In [8]:
c2 = Char(120)
println(c2)

i1 = UInt8(trunc(3.14))
println(i1)

f1 = parse(Float64, "1")
println(f1)

i2 = parse(Int8, "1")
println(i2)
x
3
1.0
1
In [9]:
i1 = UInt8(3.14)
println(i1)
InexactError: UInt8(3.14)

Stacktrace:
 [1] UInt8(::Float64) at ./float.jl:689
 [2] top-level scope at In[9]:1
 [3] include_string(::Function, ::Module, ::String, ::String) at ./loading.jl:1091

String

In [10]:
s1 = "just some random words\n"
println(length(s1))

println(s1[1])
println(s1[end])
println(s1[1:4])
s2 = string("Zikang", "Xiong")
println(s2)
println("AAA" * "BBB")
i3 = 2
i4 = 3
println("$i3 + $i4 = $(i3 + i4)")
23
j


just
ZikangXiong
AAABBB
2 + 3 = 5
In [12]:
s3 = """I
have
many
lines"""
println(s3)

println("AA" > "BB")
println(findfirst(isequal('i'), "Keigo"))
println(occursin("key", "monkey"))
I
have
many
lines
false
3
true

Condition

In [13]:
age = 12
if age >= 12 && age <= 18
    println("A")
elseif age >= 18 && age <= 20
    println("B")
else
    println("C")
end
A

Loop

In [16]:
i = 1
while i < 20
    if (i % 2) == 0
        println(i)
        global i += 1
        continue
    end
    global i += 1
    if i >= 10
        break
    end
end
2
4
6
8
In [24]:
for i = 1:5
    println(i)
end
for i in [2, 4, 6]
    println(i)
end

for i = i:5, j = 2:2:10
    println((i, j))
end
1
2
3
4
5
2
4
6

Array

In [25]:
a = zeros(Int32, 2, 2)
a2 = Array{Int32}(undef, 5)
a2 = Float64[]

a4 = [1, 2, 3]
println(a4[1])
println(a4[end])
println(5 in a4)
println(findfirst(isequal(2), a4))
f(a) = (a >= 2) ? true : false
println(findall(f, a4))
println(count(f, a4))
1
3
false
2
[2, 3]
2
In [27]:
println(size(a4))
println(length(a4))
println(sum(a4))
splice!(a4, 2:1, [8, 9])
println(a4)
splice!(a4, 2:3)
println(a4)
println(maximum(a4))
println(minimum(a4))
println(a4 * 2)
println(a4)
(3,)
3
6
[1, 8, 9, 2, 3]
[1, 2, 3]
3
1
[2, 4, 6]
[1, 2, 3]
In [29]:
a5 = [1, 3.14, "Hello"]
a6 = [sin, cos, tan]
for n in a6
    println(n(0))
end

a7 = [1 2 3; 4 5 6]
for n = 1:2, m = 1:3
    @printf("%d ", a7[n, m])
end
println()
0.0
1.0
0.0
1 2 3 4 5 6 
In [30]:
println(a7[:, 2])
println(a7[2, :])
[2, 5]
[4, 5, 6]
In [34]:
a8 = collect(1:5)
a9 = collect(2:2:10)

for n in a9 println(n) end

a10 = [n^2 for n in 1:5]
println(a10)
2
4
6
8
10
[1, 4, 9, 16, 25]
In [35]:
push!(a10, 36)
a11 = [n*m for n in 1:5, m in 1:5]
println(a11)

a12 = rand(0:9, 5, 5)
for n = 1:5
    for m = 1:5
        print(a12[n, m])
    end
    println()
end
[1 2 3 4 5; 2 4 6 8 10; 3 6 9 12 15; 4 8 12 16 20; 5 10 15 20 25]
94818
11650
67778
29135
01780

Tuple

In [40]:
t1 = (1, 2, 3, 4)
println(t1)
println(t1[1])
for i in t1
    println(i)
end

t2 = ((1,2), (3,4))
println(t2[1][1])

# named tuple
t3 = (sue = ("Sue", 100), paul = ("Paul", 23))
println(t3.sue)
(1, 2, 3, 4)
1
1
2
3
4
1
("Sue", 100)

Dictionary

In [46]:
d1 = Dict("pi"=>3.4, "e"=>2.718)
println(d1["pi"])
d1["golden"] = 1.618
delete!(d1, "pi")
println(haskey(d1, "pi"))

println(in("pi"=>3.14)(d1))

println(keys(d1))
println(values(d1))

for kv in d1
    println(kv)
end

for (k, v) in d1
    println((k, v))
end
3.4
false
false
["golden", "e"]
[1.618, 2.718]
"golden" => 1.618
"e" => 2.718
("golden", 1.618)
("e", 2.718)

Set

In [47]:
st1 = Set(["Jim", "Pam", "Jim"])
println(st1)
Set(["Pam", "Jim"])
In [51]:
push!(st1, "Michael")
println(in("Dwight", st1))
st2 = Set(["Stanley", "Meredith"])

println(union(st1, st2))
println(intersect(st1, st2))

# st1 - st2
println(setdiff(st1, st2))
false
Set(["Pam", "Stanley", "Jim", "Michael", "Meredith"])
Set{String}()
Set(["Pam", "Jim", "Michael"])

Function

In [52]:
getSum(x, y) = x + y
x, y = 1, 2

@printf("%d + %d = %d\n", x, y, getSum(x, y))
1 + 2 = 3
In [54]:
function canIVote(age=16)
    if age > 18
        println("Can Vote")
    else
        println("Cannot")
    end
end

canIVote(23)
Can Vote
In [56]:
v1 = 5
function changeV1(v1)
    global v1 = 10
end

changeV1(v1)
println(v1)
10
In [57]:
function getSum2(args...)
    sum = 0 
    for a in args
        sum += a
    end
    println(sum)
end

getSum2(1, 2, 3, 4)
10
In [59]:
function next2(val)
    return (val +1, val +2)
end
println(next2(1))
(2, 3)
In [60]:
function getSum3(num1::Number, num2::Number)
    return num1 + num2
end

function getSum3(num1::String, num2::String)
    return parse(Int32, num1) + parse(Int32, num2) 
end

println(getSum3(1, 2))
println(getSum3("1", "2"))
3
3
In [62]:
# Anonymous functions
v2 = map(x -> x * x, [1, 2, 3])
v2
Out[62]:
3-element Array{Int64,1}:
 1
 4
 9
In [64]:
v3 = map((x, y) -> x + y, [1, 2], [3, 4])
v3
Out[64]:
2-element Array{Int64,1}:
 4
 6
In [65]:
v4 = reduce(+, 1:100)
v4
Out[65]:
5050
In [66]:
sentence = "This is a string"
sArray = split(sentence)
longest = reduce((x, y) -> length(x) > length(y) ? x : y, sArray)
longest
Out[66]:
"string"

Math

image.png

In [67]:
x = 2
println(2x)
4
In [74]:
a13 = [1, 2, 3] .* [1, 2, 3]
Out[74]:
3-element Array{Int64,1}:
 1
 4
 9

Enum

In [75]:
@enum Color begin
    red = 1
    blum = 2
    green = 3
end

favColor = green::Color
println(favColor)
green

Symbol

In [77]:
Dict(:Good=>1)
Out[77]:
Dict{Symbol,Int64} with 1 entry:
  :Good => 1

Struct

In [84]:
struct Customer1
    name::String
    balance::Float32
    id::Int
end

bob = Customer1("Bob Smith", 10.50, 123)
println(bob.name)

bob.name = "aa"
Bob Smith
setfield! immutable struct of type Customer1 cannot be changed

Stacktrace:
 [1] setproperty!(::Customer1, ::Symbol, ::String) at ./Base.jl:34
 [2] top-level scope at In[84]:10
 [3] include_string(::Function, ::Module, ::String, ::String) at ./loading.jl:1091
In [85]:
mutable struct Customer2
    name::String
    balance::Float32
    id::Int
end

bob = Customer2("Bob Smith", 10.50, 123)
println(bob.name)

bob.name = "aa"
Bob Smith
Out[85]:
"aa"

Abstract Type

In [87]:
abstract type Animal end

struct Dog <: Animal
    name::String
    bark::String
end

struct Cat <: Animal
    name::String
    meow::String
end

bowser = Dog("Bowser", "Ruff")
muffin = Cat("Muffin", "Meow")

function makeSound(animal::Dog)
    println("$(animal.name) says $(animal.bark)")
end

function makeSound(animal::Cat)
    println("$(animal.name) says $(animal.meow)")
end

makeSound(bowser)
makeSound(muffin)
Bowser says Ruff
Muffin says Meow

Handle Error

image.png

File IO

In [89]:
open("res/random2.txt", "w") do file
    write(file, " test1\n test2 \n test3")
end

open("res/random2.txt") do file
    data = read(file, String)
    println(data)
end

open("res/random2.txt") do file
    for line in eachline(file)
        println(line)
    end
end
 test1
 test2 
 test3
 test1
 test2 
 test3

Macro

video
Take a piece of code, and translate it into another piece of code.

In [101]:
# quote code
expr = :(1 + 2)
expr2 = quote
    1 + 2
end
Out[101]:
quote
    #= In[101]:4 =#
    1 + 2
end
In [93]:
typeof(expr)
Out[93]:
Expr
In [94]:
expr.head
Out[94]:
:call
In [95]:
expr.args
Out[95]:
3-element Array{Any,1}:
  :+
 1
 2
In [102]:
expr.args[2] = :x
Out[102]:
:x
In [103]:
expr
Out[103]:
:(x + 2)
In [90]:
macro doMore(n, exp)
    quote 
        for i = 1:$(esc(n))
            $(esc(exp))
        end
    end
end

@doMore(2, println("Hello"))
Hello
Hello
In [91]:
macro doWhile(exp)
    @assert exp.head == :while
    esc(quote 
    $(exp.args[2])
    $exp
    end)
end

z = 0 
@doWhile while z < 10
    global z += 1
    println(z)
end
1
2
3
4
5
6
7
8
9
10