Basics
Hello World
println adds a newline, print does not
println("Hello, World!")
print("No newline")Comments
#= =# for multi-line comments
# Single-line comment
#=
Multi-line
comment
=#
# Docstring
"""docstring"""REPL
ans stores the previous result
$ julia
julia> 1 + 1
2
julia> ans # previous result
2String Interpolation
$ for variables, $(expression) for expressions
name = "Alice"
age = 30
println("$name is $age")
println("$(age * 2)")Chained Comparisons
Julia supports chained comparisons
x = 5
1 < x < 10 # true
1 <= x <= 10 # trueVariables
Variable Assignment
Supports Unicode variable names
x = 10
name = "Alice"
π = 3.14159 # supports Unicode
δ = 0.001Constants
const declares a global constant
const PI = 3.14159
const MAX_SIZE = 100
# const declares a constantType Annotations
:: for type annotations
x::Int = 10
y::Float64 = 3.14
function f(x::Int)::String
string(x)
endMultiple Assignment
Supports multiple assignment
a, b, c = 1, 2, 3
x, y = y, x # swap
(a, b) = (1, 2)Types
Basic Types
typeof gets the type
typeof(42) # Int64
typeof(3.14) # Float64
typeof("hi") # String
typeof(true) # Bool
typeof('a') # CharType Conversion
Use type name as conversion function
Int(3.14) # 3
Float64(3) # 3.0
String(42) # "42"
Char(65) # 'A'Abstract Types
abstract type defines an abstract type
abstract type Animal end
abstract type Dog <: Animal end
# <: denotes subtype relationshipStructs
struct is immutable
struct Point
x::Float64
y::Float64
end
p = Point(1.0, 2.0)
p.x # 1.0Mutable Structs
mutable struct allows field modification
mutable struct Counter
count::Int
end
c = Counter(0)
c.count += 1Parametric Types
T is a type parameter
struct Point{T}
x::T
y::T
end
p = Point{Float64}(1.0, 2.0)
q = Point{Int}(1, 2)Multiple Dispatch
Function Overloading
Julia core feature: multiple dispatch
function describe(x::Int)
"integer: $x"
end
function describe(x::String)
"string: $x"
end
describe(42) # "integer: 42"
describe("hi") # "string: hi"Parametric Methods
where specifies type parameters
function norm(p::Point{T}) where T
sqrt(p.x^2 + p.y^2)
end
# Works for all types TFallback Methods
Method without type annotations acts as default
function describe(x)
"unknown: $x"
end
# No type annotation, matches all argumentsMethod Ambiguity
Be careful to avoid method ambiguity
f(x::Int, y) = 1
f(x, y::Int) = 2
# f(1, 1) raises an ambiguity error
# Need to define f(x::Int, y::Int) = 3Functions
Function Definition
return is optional, returns the last expression
function add(a, b)
return a + b
end
# Shorthand
add(a, b) = a + bAnonymous Functions
-> defines an anonymous function
f = x -> x^2
f(5) # 25
map(x -> x * 2, [1, 2, 3])Multiple Return Values
Returns a tuple for multiple values
function divrem2(a, b)
return a ÷ b, a % b
end
q, r = divrem2(10, 3)Keyword Arguments
After ; are keyword arguments
function plot(x, y; style="line", color="blue")
# style and color are keyword arguments
end
plot(1:10, 1:10, color="red")Variadic Arguments
... collects variadic arguments
function sumall(args...)
sum(args)
end
sumall(1, 2, 3, 4) # 10do Block
do block passes an anonymous function
map([1, 2, 3]) do x
x ^ 2
end
# Equivalent to map(x -> x^2, [1,2,3])Control Flow
if-elseif-else
Conditional expression
if x > 0
println("positive")
elseif x < 0
println("negative")
else
println("zero")
endTernary Operator
condition ? true_value : false_value
result = x > 0 ? "pos" : "neg"
# Chained
result = x > 0 ? "pos" : x < 0 ? "neg" : "zero"for Loop
for in iteration
for i in 1:5
println(i)
end
for (i, v) in enumerate(arr)
println(i, v)
endwhile Loop
while loop
i = 1
while i <= 5
println(i)
i += 1
endbreak and continue
&& short-circuit evaluation for conditions
for i in 1:10
i == 5 && break
i % 2 == 0 && continue
println(i)
endArrays
Creating Arrays
Arrays are column-major
a = [1, 2, 3, 4, 5]
b = [1 2 3; 4 5 6] # 2x3 matrix
c = zeros(3, 3)
d = ones(5)
e = rand(2, 2)Array Indexing
Indices start from 1
a = [10, 20, 30, 40, 50]
a[1] # 10 (1-based)
a[end] # 50
a[2:4] # [20, 30, 40]
a[[1, 3]] # [10, 30]Array Operations
! suffix means in-place modification
push!(a, 60) # add to end
pop!(a) # remove from end
append!(a, b) # concatenate
sort(a) # sort (returns new array)
sort!(a) # in-place sortArray Comprehension
Similar to list comprehension
[x^2 for x in 1:5]
# [1, 4, 9, 16, 25]
[x^2 for x in 1:10 if x % 2 == 0]
# [4, 16, 36, 64, 100]Broadcasting
. operator for broadcasting
a = [1, 2, 3]
a .^ 2 # [1, 4, 9]
f.(a) # apply f to each element
a .+ 10 # [11, 12, 13]Tuples
Tuples
Tuples are immutable
t = (1, 2, 3)
t[1] # 1
t[2] # 2
# Named tuple
nt = (name="Alice", age=30)
nt.name # "Alice"Destructuring
Tuple destructuring assignment
a, b, c = (1, 2, 3)
(first, second) = (10, 20)
# Ignore
_, y = (1, 2)Dictionaries
Creating Dictionaries
Dict creates a dictionary
d = Dict("a" => 1, "b" => 2)
d2 = Dict(:name => "Alice", :age => 30)
d["c"] = 3 # addAccess and Modify
[] for access and modification
d = Dict("a" => 1, "b" => 2)
d["a"] # 1
d["a"] = 10 # modify
delete!(d, "b") # deleteIteration
Iterate over key-value pairs
for (k, v) in d
println(k, " => ", v)
end
keys(d) # all keys
values(d) # all valuesDictionary Operations
Common dictionary functions
haskey(d, "a") # true
get(d, "x", 0) # default value 0
get!(d, "x", 0) # add if missing
merge(d1, d2) # mergeStrings
String Basics
String indices may be non-contiguous (UTF-8)
s = "Hello World"
length(s) # 11
s[1] # 'H'
s[1:5] # "Hello"
lastindex(s) # 11String Operations
Common string functions
uppercase("hi") # "HI"
lowercase("HI") # "hi"
reverse("hello") # "olleh"
strip(" hi ") # "hi"Find and Replace
Find and replace
s = "Hello World"
findfirst("World", s) # 7:11
occursin("World", s) # true
replace(s, "World" => "Julia") # "Hello Julia"Split and Join
split and join
split("a,b,c", ",") # ["a", "b", "c"]
join(["a", "b"], "-") # "a-b"
split("hello", "") # ['h','e','l','l','o']Math Functions
Basic Math
Built-in math functions
abs(-5) # 5
sqrt(16) # 4.0
cbrt(27) # 3.0
sign(-5) # -1
floor(3.7) # 3.0
ceil(3.2) # 4.0Trigonometric Functions
In radians
sin(π/2) # 1.0
cos(0) # 1.0
tan(π/4) # 1.0
asin(1) # 1.5707... (π/2)Logarithm and Exponential
log is the natural logarithm
log(ℯ) # 1.0 (natural log)
log2(8) # 3.0
log10(100) # 2.0
exp(1) # 2.718... (ℯ)Special Values
Math constants and special values
π # 3.14159...
ℯ # 2.71828...
Inf # positive infinity
NaN # not a number
im # imaginary unitLinear Algebra
Matrix Operations
LinearAlgebra standard library
using LinearAlgebra
A = [1 2; 3 4]
A' # transpose
inv(A) # inverse matrix
det(A) # determinant
rank(A) # rankMatrix Decomposition
Various matrix decompositions
A = [1.0 2.0; 3.0 4.0]
F = lu(A) # LU decomposition
F = qr(A) # QR decomposition
F = svd(A) # SVD decomposition
F = eigen(A) # eigendecompositionVector Operations
Vector operations
v1 = [1, 2, 3]
v2 = [4, 5, 6]
dot(v1, v2) # dot product
cross(v1, v2) # cross product
norm(v1) # norm
v1 ⋅ v2 # dot product (Unicode)Statistics
Basic Statistics
Statistics standard library
using Statistics
data = [1, 2, 3, 4, 5]
mean(data) # 3.0
median(data) # 3.0
std(data) # standard deviation
var(data) # varianceQuantiles
Quantile calculation
using Statistics
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
quantile(data, 0.25) # 3.25
quantile(data, 0.5) # 5.5
quantile(data, 0.75) # 7.75Correlation and Covariance
Correlation coefficient and covariance
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
cor(x, y) # 1.0 (correlation coefficient)
cov(x, y) # covariancePlotting
Basic Plotting
Plots.jl is the main plotting library
using Plots
x = 1:10
y = x .^ 2
plot(x, y, title="Quadratic", label="x^2")Scatter Plot
scatter draws a scatter plot
using Plots
x = rand(50)
y = rand(50)
scatter(x, y, markersize=5, color=:red)Subplots
layout controls subplot layout
using Plots
p1 = plot(1:10, 1:10)
p2 = plot(1:10, (1:10).^2)
plot(p1, p2, layout=(2, 1))Save Image
savefig saves the image
using Plots
p = plot(sin, 0, 2π)
savefig(p, "sine.png")DataFrames
Create DataFrame
DataFrames.jl is similar to pandas
using DataFrames
df = DataFrame(
name = ["Alice", "Bob", "Carol"],
age = [25, 30, 35],
city = ["NYC", "LA", "SF"]
)Access Data
Row and column access
df.name # column
df[1, :] # first row
df[:, :age] # age column
df[1:2, :] # first two rowsFilter and Sort
Filtering and sorting
using DataFrames
filter(:age => >(28), df) # age > 28
sort(df, :age) # sort by age
sort(df, :age, rev=true) # descendingGroup and Aggregate
groupby + combine for grouped aggregation
using DataFrames, Statistics
combine(groupby(df, :city), :age => mean => :avg_age)File I/O
Read and Write Text
open do block auto-closes the file
# Write
open("output.txt", "w") do f
write(f, "Hello World")
end
# Read
content = read("input.txt", String)Read Line by Line
eachline iterates line by line
for line in eachline("data.txt")
println(line)
end
# Or
lines = readlines("data.txt")CSV Files
CSV.jl handles CSV files
using CSV, DataFrames
df = CSV.read("data.csv", DataFrame)
CSV.write("output.csv", df)JSON Files
JSON.jl handles JSON
using JSON
data = JSON.parsefile("data.json")
JSON.print("output.json", data)Modules
Define Module
export declares public interface
module MyModule
export greet, add
greet(name) = println("Hello $name")
add(a, b) = a + b
end # moduleImport Module
Difference between using and import
using MyModule # imports exported names
using MyModule: greet # selective import
import MyModule # needs MyModule.greet
import MyModule: add # selective importStandard Modules
Standard library modules
using Dates # date and time
using LinearAlgebra # linear algebra
using Statistics # statistics
using Random # random numbersMacros
Define Macro
Macros operate on AST at compile time
macro sayhi(name)
return :(println("Hi, $name"))
end
@sayhi "Alice" # Hi, AliceExpression Quoting
:() creates an expression object
ex = :(1 + 2)
# :(1 + 2)
dump(ex)
# Expr
# head: Symbol call
# args: Array[...]Common Macros
Built-in common macros
@time sleep(1) # timing
@assert 1 == 1 # assertion
@show x # print variable name and value
@elapsed sleep(0.1) # return only time
@which sin(1) # view method locationMetaprogramming
Expression Construction
Expr constructs an AST
ex = Expr(:call, :+, 1, 2)
eval(ex) # 3
# Equivalent to
eval(:(1 + 2)) # 3Code Generation
Loop to generate code
for op in (:+, :-, :*, :/)
eval(:(f($op, a, b) = $op(a, b)))
end
f(+, 1, 2) # 3Macro Hygiene
Macro hygiene avoids variable conflicts
macro setx(val)
return :(x = $val)
end
# Variables in macros are hygienic and won't pollute the caller's scopeParallel Computing
Multi-threading
@threads macro for parallel loops
# Start: julia --threads=4
Threads.nthreads() # 4
Threads.@threads for i in 1:100
results[i] = compute(i)
endDistributed Computing
Distributed standard library
using Distributed
addprocs(4) # add 4 worker processes
@everywhere function work(x)
x ^ 2
end
pmap(work, 1:100) # parallel mapRemote Call
Asynchronous remote call
using Distributed
ref = @spawnat :any sqrt(16)
fetch(ref) # 4.0
# @spawnat executes on a specified processCoroutines
Task
Task is Julia's coroutine
t = Task(() -> begin
println("running")
return 42
end)
schedule(t)
wait(t)Channel
Channel for communication between coroutines
ch = Channel(32)
put!(ch, 1)
put!(ch, 2)
take!(ch) # 1
take!(ch) # 2Producer-Consumer
Coroutines implement producer-consumer
function producer(ch)
for i in 1:5
put!(ch, i)
end
end
task = @task producer(Channel(10))
for val in task
println(val)
endException Handling
try-catch
try-catch-finally
try
risky()
catch e
println("Error: $e")
finally
cleanup()
endThrow Exception
throw raises an exception object
throw(ErrorException("something wrong"))
throw(DomainError(-1, "negative"))
error("generic error")Custom Exception
Inherit from Exception type
struct MyError <: Exception
msg::String
end
throw(MyError("custom error"))Assertion
@assert macro
@assert x > 0 "x must be positive"
# Throws AssertionError when condition is falseRegex
Regular Expressions
r"" creates a regex
re = r"\d+"
occursin(re, "abc123") # true
match(re, "abc123") # RegexMatchMatch
match returns the match result
m = match(r"(\w+)@(\w+)", "user@host")
m.match # "user@host"
m.captures # ["user", "host"]
m[1] # "user"Find All
eachmatch iterates over all matches
for m in eachmatch(r"\d+", "a1b2c3")
println(m.match)
end
# 1, 2, 3Replace
replace supports regex
replace("a1b2c3", r"\d" => "#")
# "a#b#c#"
replace("hello", r"l" => "L" => count=1)
# "heLlo"DateTime
Create Date
Dates standard library
using Dates
now() # current time
Date(2024, 1, 15) # date
DateTime(2024, 1, 15, 10, 30) # datetimeFormatting
Formatting and parsing
using Dates
dt = now()
Dates.format(dt, "yyyy-mm-dd HH:MM:SS")
Date("2024-01-15", "yyyy-mm-dd")Date Arithmetic
Time interval types
using Dates
d1 = Date(2024, 1, 1)
d2 = d1 + Day(30) # add 30 days
diff = d2 - d1 # 30 days
Day(1) + Hour(12) # datetime arithmeticPackages
Install Packages
Pkg.add installs packages
using Pkg
Pkg.add("Plots")
Pkg.add(["DataFrames", "CSV"])
Pkg.rm("Plots") # removePackage Management
Common Pkg commands
Pkg.status() # view installed
Pkg.update() # update all
Pkg.instantiate() # install per Project.toml
Pkg.activate("env") # activate environmentEnvironments
Project environment management
# Project.toml defines dependencies
# Manifest.toml locks versions
Pkg.activate("myproject") # activate environment
Pkg.resolve() # resolve dependenciesPkg Manager
REPL Pkg Mode
] enters Pkg REPL mode
julia> ]
pkg> add Plots
pkg> rm Plots
pkg> status
pkg> update
pkg> test PlotsCreate Package
generate creates a package skeleton
pkg> generate MyPackage
# Directory structure
# MyPackage/
# Project.toml
# src/MyPackage.jlDevelopment Mode
dev installs in development mode
pkg> dev ./MyPackage # local development
pkg> dev MyPackage # dev version from GitHub
pkg> free MyPackage # exit development modeInteroperability
Call C
ccall calls C functions
ccall((:sqrt, "libm"), Float64, (Float64,), 16.0)
# 4.0Call Python
PyCall.jl calls Python
using PyCall
np = pyimport("numpy")
np.array([1, 2, 3])
np.mean([1, 2, 3])Call R
RCall.jl calls R
using RCall
R"sd(c(1,2,3,4,5))" # call R codeGPU Computing
CUDA Arrays
CUDA.jl supports NVIDIA GPUs
using CUDA
a = CUDA.ones(1000)
b = CUDA.zeros(1000)
c = a .+ b # operations on GPUGPU Kernel
@cuda launches a GPU kernel
using CUDA
function kernel!(a)
i = threadIdx().x
if i <= length(a)
@inbounds a[i] *= 2
end
return
end
@cuda threads=256 kernel!(a)AMD GPU
AMDGPU.jl supports AMD GPUs
using AMDGPU
a = ROCArray(ones(100))
b = a .* 2 # operations on AMD GPUSnippets de Julia relacionados
Copy-paste ready code for common tasks.
Broadcasting e vetorização
Aplica uma função elemento a elemento sobre arrays com sintaxe de ponto e @.
Despacho múltiplo
Seleciona métodos pelos tipos em tempo de execução de todos os argumentos, não apenas o receptor.
Tipos paramétricos e desempenho
Define contêineres genéricos e estáveis quanto ao tipo que compilam para código especializado.
Macros e expressões
Manipula árvores de sintaxe do Julia como dados de primeira classe via :expr e macro.
Multithreading e computação distribuída
Paraleliza laços com @threads e descarrega tarefas com @spawn / pmap.
Operações com DataFrame (DataFrames.jl)
Filtra, transforma, agrupa e junta dados tabulares com DataFrames.jl.
Dicas de desempenho: @inbounds, @fastmath, views
Escreve Julia na velocidade do C removendo checagens de limites, evitando alocações e usando views.
Resolver EDOs com DifferentialEquations.jl
Define e resolve numericamente uma EDO de valor inicial com passo adaptativo.
Was this helpful?