Skip to content

Julia Cheatsheet

Julia is a high-level, high-performance dynamic language for technical computing.

01

Basics

Hello World

println adds a newline, print does not

julia
println("Hello, World!")
print("No newline")

Comments

#= =# for multi-line comments

julia
# Single-line comment

#=
  Multi-line
  comment
=#

# Docstring
"""docstring"""

REPL

ans stores the previous result

julia
$ julia
julia> 1 + 1
2
julia> ans  # previous result
2

String Interpolation

$ for variables, $(expression) for expressions

julia
name = "Alice"
age = 30
println("$name is $age")
println("$(age * 2)")

Chained Comparisons

Julia supports chained comparisons

julia
x = 5
1 < x < 10  # true
1 <= x <= 10  # true
02

Variables

Variable Assignment

Supports Unicode variable names

julia
x = 10
name = "Alice"
π = 3.14159  # supports Unicode
δ = 0.001

Constants

const declares a global constant

julia
const PI = 3.14159
const MAX_SIZE = 100
# const declares a constant

Type Annotations

:: for type annotations

julia
x::Int = 10
y::Float64 = 3.14
function f(x::Int)::String
  string(x)
end

Multiple Assignment

Supports multiple assignment

julia
a, b, c = 1, 2, 3
x, y = y, x  # swap
(a, b) = (1, 2)
03

Types

Basic Types

typeof gets the type

julia
typeof(42)       # Int64
typeof(3.14)     # Float64
typeof("hi")     # String
typeof(true)     # Bool
typeof('a')      # Char

Type Conversion

Use type name as conversion function

julia
Int(3.14)    # 3
Float64(3)   # 3.0
String(42)   # "42"
Char(65)     # 'A'

Abstract Types

abstract type defines an abstract type

julia
abstract type Animal end
abstract type Dog <: Animal end
# <: denotes subtype relationship

Structs

struct is immutable

julia
struct Point
  x::Float64
  y::Float64
end

p = Point(1.0, 2.0)
p.x  # 1.0

Mutable Structs

mutable struct allows field modification

julia
mutable struct Counter
  count::Int
end

c = Counter(0)
c.count += 1

Parametric Types

T is a type parameter

julia
struct Point{T}
  x::T
  y::T
end

p = Point{Float64}(1.0, 2.0)
q = Point{Int}(1, 2)
04

Multiple Dispatch

Function Overloading

Julia core feature: multiple dispatch

julia
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

julia
function norm(p::Point{T}) where T
  sqrt(p.x^2 + p.y^2)
end

# Works for all types T

Fallback Methods

Method without type annotations acts as default

julia
function describe(x)
  "unknown: $x"
end

# No type annotation, matches all arguments

Method Ambiguity

Be careful to avoid method ambiguity

julia
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) = 3
05

Functions

Function Definition

return is optional, returns the last expression

julia
function add(a, b)
  return a + b
end

# Shorthand
add(a, b) = a + b

Anonymous Functions

-> defines an anonymous function

julia
f = x -> x^2
f(5)  # 25

map(x -> x * 2, [1, 2, 3])

Multiple Return Values

Returns a tuple for multiple values

julia
function divrem2(a, b)
  return a ÷ b, a % b
end

q, r = divrem2(10, 3)

Keyword Arguments

After ; are keyword arguments

julia
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

julia
function sumall(args...)
  sum(args)
end

sumall(1, 2, 3, 4)  # 10

do Block

do block passes an anonymous function

julia
map([1, 2, 3]) do x
  x ^ 2
end
# Equivalent to map(x -> x^2, [1,2,3])
06

Control Flow

if-elseif-else

Conditional expression

julia
if x > 0
  println("positive")
elseif x < 0
  println("negative")
else
  println("zero")
end

Ternary Operator

condition ? true_value : false_value

julia
result = x > 0 ? "pos" : "neg"

# Chained
result = x > 0 ? "pos" : x < 0 ? "neg" : "zero"

for Loop

for in iteration

julia
for i in 1:5
  println(i)
end

for (i, v) in enumerate(arr)
  println(i, v)
end

while Loop

while loop

julia
i = 1
while i <= 5
  println(i)
  i += 1
end

break and continue

&& short-circuit evaluation for conditions

julia
for i in 1:10
  i == 5 && break
  i % 2 == 0 && continue
  println(i)
end
07

Arrays

Creating Arrays

Arrays are column-major

julia
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

julia
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

julia
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 sort

Array Comprehension

Similar to list comprehension

julia
[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

julia
a = [1, 2, 3]
a .^ 2       # [1, 4, 9]
f.(a)        # apply f to each element
a .+ 10      # [11, 12, 13]
08

Tuples

Tuples

Tuples are immutable

julia
t = (1, 2, 3)
t[1]  # 1
t[2]  # 2

# Named tuple
nt = (name="Alice", age=30)
nt.name  # "Alice"

Destructuring

Tuple destructuring assignment

julia
a, b, c = (1, 2, 3)
(first, second) = (10, 20)

# Ignore
_, y = (1, 2)
09

Dictionaries

Creating Dictionaries

Dict creates a dictionary

julia
d = Dict("a" => 1, "b" => 2)
d2 = Dict(:name => "Alice", :age => 30)
d["c"] = 3  # add

Access and Modify

[] for access and modification

julia
d = Dict("a" => 1, "b" => 2)
d["a"]      # 1
d["a"] = 10 # modify
delete!(d, "b")  # delete

Iteration

Iterate over key-value pairs

julia
for (k, v) in d
  println(k, " => ", v)
end

keys(d)    # all keys
values(d)  # all values

Dictionary Operations

Common dictionary functions

julia
haskey(d, "a")    # true
get(d, "x", 0)     # default value 0
get!(d, "x", 0)    # add if missing
merge(d1, d2)      # merge
10

Strings

String Basics

String indices may be non-contiguous (UTF-8)

julia
s = "Hello World"
length(s)    # 11
s[1]         # 'H'
s[1:5]       # "Hello"
lastindex(s) # 11

String Operations

Common string functions

julia
uppercase("hi")    # "HI"
lowercase("HI")    # "hi"
reverse("hello")   # "olleh"
strip("  hi  ")     # "hi"

Find and Replace

Find and replace

julia
s = "Hello World"
findfirst("World", s)  # 7:11
occursin("World", s)   # true
replace(s, "World" => "Julia")  # "Hello Julia"

Split and Join

split and join

julia
split("a,b,c", ",")   # ["a", "b", "c"]
join(["a", "b"], "-")  # "a-b"
split("hello", "")     # ['h','e','l','l','o']
11

Math Functions

Basic Math

Built-in math functions

julia
abs(-5)      # 5
sqrt(16)    # 4.0
cbrt(27)    # 3.0
sign(-5)    # -1
floor(3.7)  # 3.0
ceil(3.2)   # 4.0

Trigonometric Functions

In radians

julia
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

julia
log(ℯ)      # 1.0 (natural log)
log2(8)    # 3.0
log10(100) # 2.0
exp(1)     # 2.718... (ℯ)

Special Values

Math constants and special values

julia
π     # 3.14159...
ℯ     # 2.71828...
Inf   # positive infinity
NaN   # not a number
im    # imaginary unit
12

Linear Algebra

Matrix Operations

LinearAlgebra standard library

julia
using LinearAlgebra

A = [1 2; 3 4]
A'        # transpose
inv(A)    # inverse matrix
det(A)    # determinant
rank(A)   # rank

Matrix Decomposition

Various matrix decompositions

julia
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) # eigendecomposition

Vector Operations

Vector operations

julia
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)
13

Statistics

Basic Statistics

Statistics standard library

julia
using Statistics

data = [1, 2, 3, 4, 5]
mean(data)    # 3.0
median(data)  # 3.0
std(data)     # standard deviation
var(data)     # variance

Quantiles

Quantile calculation

julia
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.75

Correlation and Covariance

Correlation coefficient and covariance

julia
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
cor(x, y)    # 1.0 (correlation coefficient)
cov(x, y)    # covariance
14

Plotting

Basic Plotting

Plots.jl is the main plotting library

julia
using Plots

x = 1:10
y = x .^ 2
plot(x, y, title="Quadratic", label="x^2")

Scatter Plot

scatter draws a scatter plot

julia
using Plots

x = rand(50)
y = rand(50)
scatter(x, y, markersize=5, color=:red)

Subplots

layout controls subplot layout

julia
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

julia
using Plots

p = plot(sin, 0, 2π)
savefig(p, "sine.png")
15

DataFrames

Create DataFrame

DataFrames.jl is similar to pandas

julia
using DataFrames

df = DataFrame(
  name = ["Alice", "Bob", "Carol"],
  age = [25, 30, 35],
  city = ["NYC", "LA", "SF"]
)

Access Data

Row and column access

julia
df.name      # column
df[1, :]     # first row
df[:, :age]  # age column
df[1:2, :]   # first two rows

Filter and Sort

Filtering and sorting

julia
using DataFrames

filter(:age => >(28), df)  # age > 28
sort(df, :age)            # sort by age
sort(df, :age, rev=true)  # descending

Group and Aggregate

groupby + combine for grouped aggregation

julia
using DataFrames, Statistics

combine(groupby(df, :city), :age => mean => :avg_age)
16

File I/O

Read and Write Text

open do block auto-closes the file

julia
# 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

julia
for line in eachline("data.txt")
  println(line)
end

# Or
lines = readlines("data.txt")

CSV Files

CSV.jl handles CSV files

julia
using CSV, DataFrames

df = CSV.read("data.csv", DataFrame)
CSV.write("output.csv", df)

JSON Files

JSON.jl handles JSON

julia
using JSON

data = JSON.parsefile("data.json")
JSON.print("output.json", data)
17

Modules

Define Module

export declares public interface

julia
module MyModule

export greet, add

greet(name) = println("Hello $name")
add(a, b) = a + b

end  # module

Import Module

Difference between using and import

julia
using MyModule     # imports exported names
using MyModule: greet  # selective import
import MyModule        # needs MyModule.greet
import MyModule: add    # selective import

Standard Modules

Standard library modules

julia
using Dates        # date and time
using LinearAlgebra # linear algebra
using Statistics     # statistics
using Random         # random numbers
18

Macros

Define Macro

Macros operate on AST at compile time

julia
macro sayhi(name)
  return :(println("Hi, $name"))
end

@sayhi "Alice"  # Hi, Alice

Expression Quoting

:() creates an expression object

julia
ex = :(1 + 2)
# :(1 + 2)

dump(ex)
# Expr
#   head: Symbol call
#   args: Array[...]

Common Macros

Built-in common macros

julia
@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 location
19

Metaprogramming

Expression Construction

Expr constructs an AST

julia
ex = Expr(:call, :+, 1, 2)
eval(ex)  # 3

# Equivalent to
eval(:(1 + 2))  # 3

Code Generation

Loop to generate code

julia
for op in (:+, :-, :*, :/)
  eval(:(f($op, a, b) = $op(a, b)))
end

f(+, 1, 2)  # 3

Macro Hygiene

Macro hygiene avoids variable conflicts

julia
macro setx(val)
  return :(x = $val)
end

# Variables in macros are hygienic and won't pollute the caller's scope
20

Parallel Computing

Multi-threading

@threads macro for parallel loops

julia
# Start: julia --threads=4
Threads.nthreads()  # 4

Threads.@threads for i in 1:100
  results[i] = compute(i)
end

Distributed Computing

Distributed standard library

julia
using Distributed
addprocs(4)  # add 4 worker processes

@everywhere function work(x)
  x ^ 2
end

pmap(work, 1:100)  # parallel map

Remote Call

Asynchronous remote call

julia
using Distributed

ref = @spawnat :any sqrt(16)
fetch(ref)  # 4.0

# @spawnat executes on a specified process
21

Coroutines

Task

Task is Julia's coroutine

julia
t = Task(() -> begin
  println("running")
  return 42
end)

schedule(t)
wait(t)

Channel

Channel for communication between coroutines

julia
ch = Channel(32)

put!(ch, 1)
put!(ch, 2)
take!(ch)  # 1
take!(ch)  # 2

Producer-Consumer

Coroutines implement producer-consumer

julia
function producer(ch)
  for i in 1:5
    put!(ch, i)
  end
end

task = @task producer(Channel(10))
for val in task
  println(val)
end
22

Exception Handling

try-catch

try-catch-finally

julia
try
  risky()
catch e
  println("Error: $e")
finally
  cleanup()
end

Throw Exception

throw raises an exception object

julia
throw(ErrorException("something wrong"))
throw(DomainError(-1, "negative"))
error("generic error")

Custom Exception

Inherit from Exception type

julia
struct MyError <: Exception
  msg::String
end

throw(MyError("custom error"))

Assertion

@assert macro

julia
@assert x > 0 "x must be positive"
# Throws AssertionError when condition is false
23

Regex

Regular Expressions

r"" creates a regex

julia
re = r"\d+"
occursin(re, "abc123")  # true
match(re, "abc123")     # RegexMatch

Match

match returns the match result

julia
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

julia
for m in eachmatch(r"\d+", "a1b2c3")
  println(m.match)
end
# 1, 2, 3

Replace

replace supports regex

julia
replace("a1b2c3", r"\d" => "#")
# "a#b#c#"

replace("hello", r"l" => "L" => count=1)
# "heLlo"
24

DateTime

Create Date

Dates standard library

julia
using Dates

now()                    # current time
Date(2024, 1, 15)       # date
DateTime(2024, 1, 15, 10, 30)  # datetime

Formatting

Formatting and parsing

julia
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

julia
using Dates

d1 = Date(2024, 1, 1)
d2 = d1 + Day(30)     # add 30 days
diff = d2 - d1        # 30 days
Day(1) + Hour(12)     # datetime arithmetic
25

Packages

Install Packages

Pkg.add installs packages

julia
using Pkg
Pkg.add("Plots")
Pkg.add(["DataFrames", "CSV"])
Pkg.rm("Plots")  # remove

Package Management

Common Pkg commands

julia
Pkg.status()    # view installed
Pkg.update()    # update all
Pkg.instantiate()  # install per Project.toml
Pkg.activate("env")  # activate environment

Environments

Project environment management

julia
# Project.toml defines dependencies
# Manifest.toml locks versions

Pkg.activate("myproject")  # activate environment
Pkg.resolve()  # resolve dependencies
26

Pkg Manager

REPL Pkg Mode

] enters Pkg REPL mode

julia
julia> ]
pkg> add Plots
pkg> rm Plots
pkg> status
pkg> update
pkg> test Plots

Create Package

generate creates a package skeleton

julia
pkg> generate MyPackage

# Directory structure
# MyPackage/
#   Project.toml
#   src/MyPackage.jl

Development Mode

dev installs in development mode

julia
pkg> dev ./MyPackage  # local development
pkg> dev MyPackage    # dev version from GitHub
pkg> free MyPackage   # exit development mode
27

Interoperability

Call C

ccall calls C functions

julia
ccall((:sqrt, "libm"), Float64, (Float64,), 16.0)
# 4.0

Call Python

PyCall.jl calls Python

julia
using PyCall
np = pyimport("numpy")
np.array([1, 2, 3])
np.mean([1, 2, 3])

Call R

RCall.jl calls R

julia
using RCall
R"sd(c(1,2,3,4,5))"  # call R code
28

GPU Computing

CUDA Arrays

CUDA.jl supports NVIDIA GPUs

julia
using CUDA

a = CUDA.ones(1000)
b = CUDA.zeros(1000)
c = a .+ b  # operations on GPU

GPU Kernel

@cuda launches a GPU kernel

julia
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

julia
using AMDGPU

a = ROCArray(ones(100))
b = a .* 2  # operations on AMD GPU

Was this helpful?