Julia Cheat Sheet
Basics & REPL
julia --startup-file=no main.jl- Run a script
?sum ;ls ]add DataFrames- REPL modes: help, shell, package manager
x = 42; name = "Ada"; const G = 9.81- Variables and a constant
typeof(3), typeof(3.0), typeof("a"), typeof('a')- Int64, Float64, String, Char
println("x = $x, twice = $(2x)")- String interpolation; 2x means 2 * x
7 ÷ 2, 7 % 2, 7 / 2, 2^10- Integer division, remainder, float division, power
parse(Int, "42"), string(42), Float64(1)- Conversions
Control Flow
if x > 0 ... elseif x < 0 ... else ... end- Conditional (condition must be a Bool)
x > 0 ? "pos" : "non-pos"- Ternary operator
for i in 1:10 ... end- Loop over a range (inclusive); 10:-1:1 counts down
for (i, v) in enumerate(xs) ... end- Index and value
while cond ... end- While loop; break and continue work as usual
ok && println("yes"); x > 0 || error("bad")- Short-circuit guards
Functions
f(x) = x^2 + 1- One-line function definition
function g(a, b=2; scale=1) ... end- Optional positional and keyword arguments
x -> x * 2- Anonymous function
map(sqrt, xs); filter(iseven, xs); reduce(+, xs)- Higher-order functions
sin.(xs) xs .+ 1 @. 2xs^2 + 1- Broadcasting (element-wise) with dot syntax
push!(xs, 4)- A trailing ! means the function mutates its argument
xs |> sum; (sqrt ∘ abs)(-16)- Piping and function composition
Collections
v = [1, 2, 3]; v[1]; v[end]; v[2:end]- Vectors are 1-based; end is the last index
M = [1 2; 3 4]; M[2, 1]; size(M)- Matrix literal and indexing
zeros(3), ones(2, 2), rand(3), collect(1:5)- Array constructors
[x^2 for x in 1:5 if isodd(x)]- Comprehension
t = (1, "a"); nt = (name="Ada", age=36)- Tuple and named tuple
d = Dict("a" => 1); d["b"] = 2; get(d, "c", 0)- Dictionary
s = Set([1, 2]); 2 in s- Set and membership
Types & Multiple Dispatch
struct Point x::Float64; y::Float64 end- Immutable composite type
mutable struct Account balance::Float64 end- Mutable composite type
abstract type Shape end; struct Circle <: Shape r end- Abstract type and subtype
area(c::Circle) = π * c.r^2- Method specialized on an argument type
struct Box{T} a::T; b::T end- Parametric type
f(x::T, y::T) where {T<:Number} = x + y- Parametric method with a constraint
Base.show(io::IO, p::Point) = print(io, "(", p.x, ", ", p.y, ")")- Custom printing
methods(area); @which area(Circle(1))- Inspect methods and dispatch
Linear Algebra & Statistics
using LinearAlgebra, Statistics- Standard libraries
A * B; A'; A \ b- Matrix product, adjoint (transpose), solve Ax = b
det(A), inv(A), norm(v), dot(u, v)- Common operations
eigen(A).values; I (identity)- Eigenvalues and the identity operator
mean(xs), median(xs), std(xs)- Statistics
using Random; Random.seed!(42)- Reproducible random numbers
Performance
@time f(x)- Time and allocations (run twice: the first call compiles)
@btime f($x)- Accurate benchmark (BenchmarkTools.jl)
@code_warntype f(x)- Find type instabilities
@views s = sum(A[:, 1])- Slice without copying
y .= a .* x .+ y- In-place fused broadcast (no allocation)
julia -t auto; Threads.@threads for i in 1:n ... end- Multithreading
Packages, Errors & Macros
using Pkg; Pkg.activate("."); Pkg.add("CSV")- Project environment and adding a package
module MyMod export f; f() = 1 end- Module with an exported name
try ... catch e ... finally ... end- Error handling
throw(ArgumentError("bad")); error("msg")- Raise an error
:(a + b); Meta.parse("1 + 2")- Code as data (expressions)
macro twice(ex) :($(esc(ex)); $(esc(ex))) end- Define a macro; call it with @twice
@test f(2) == 4; @testset "name" begin ... end- Unit tests (Test standard library)