Julia Fast scientific language

Version 1.13 · source

Start here

julia
Open the REPL
julia <file.jl> <args>
Run a script
julia -e '<expr>'
Run one expression
julia --project=.
Use this folder's env
]
Package mode
?
Help mode
julia -t auto
Use all cores
include("<file.jl>")
Load a file in the REPL

Concepts

  1. Generic function name: area
  2. Dispatch all argument types
  3. Method specialized, compiled
  4. Fast native code reused after

Command line

julia
Start the interactive REPL
julia <file.jl> <args>
Run a script; args land in ARGS
julia -e '<expr>'
Evaluate an expression and exit
julia -E '<expr>'
Evaluate and print the result
julia --project=<dir>
Activate the environment in a folder
--project=. or plain --project searches parent folders for Project.toml.
julia -t <n|auto>
Set the number of threads
Also JULIA_NUM_THREADS; check with Threads.nthreads().
julia -p <n|auto>
Add local worker processes
julia -i <file.jl>
Run a file, then stay in the REPL
julia -L <file.jl>
Load a file before the REPL starts
julia --startup-file=no
Skip ~/.julia/config/startup.jl

REPL

?
Help mode: docs for a name
]
Package mode
;
Shell mode: run a shell command
Backspace
Leave a special mode
Ctrl+D / exit()
Quit Julia
Ctrl+C
Interrupt running code
ans
Result of the last expression
Ctrl+R
Search history
methods(<f>)
List methods of a function
@time <expr>
Time an expression and show allocations
Revise
Reload edited code without restarting
Install the Revise package and run using Revise first.
include("<file.jl>")
Evaluate a file in this session
using <Pkg>
Load a package's exports
import <Pkg>
Load a package, names stay qualified

Packages

add <pkg>
Add a package to the environment
rm <pkg>
Remove a package
status
Show the environment (alias st)
up
Update packages
activate <dir>
Switch to the environment in a folder
activate --temp
Switch to a temporary environment
instantiate
Install what Manifest.toml lists
Run after cloning a project.
test
Run the project's tests
precompile
Precompile dependencies now
dev <path or name>
Work on a local copy of a package
st -o
Show outdated packages
add <pkg>@<ver>
Add a specific version
generate <Name>
Create a minimal package
using Pkg; Pkg.add("<pkg>")
Pkg functions from code

Basics

x = 3; y = x^2
Assign and exponentiate
println("x = $x")
Print with interpolation
"a" * "b"
Concatenate strings
+ does not work on strings.
if a < b ... elseif ... else ... end
Conditional
for i in 1:10 ... end
Loop over a range
while <cond> ... end
Loop while true
function f(x, y=2; k=1) ... end
Function with default and keyword args
f(x) = x^2
Short function form
x -> x^2
Anonymous function
(1, "a")
Tuple, immutable
Dict("a" => 1)
Dictionary
d["a"]
Index a dictionary
get(d, k, <default>)
Lookup with a fallback
1:2:9
Range with step
typeof(x)
Type of a value
try ... catch e ... finally ... end
Handle errors

Arrays

[1, 2, 3]
Vector literal
[1 2; 3 4]
Matrix literal
A[i, j]
Element at row i, column j
A[2:end, :]
Slice; end is the last index
push!(v, x)
Append to a vector
length(v) / size(A)
Element count / dimensions
zeros(n, m) / ones(n)
Arrays of 0 or 1
rand(n, m)
Random array
collect(1:5)
Turn a range into a vector
[f(x) for x in v if <cond>]
Comprehension
f.(v)
Broadcast f over elements
v .+ 1
Elementwise operator
map(f, v) / filter(f, v)
Apply / keep matching
reduce(+, v) / sum(v)
Fold into one value
sort(v) / sort!(v)
Sorted copy / in place
A'
Transpose
A * B / A .* B
Matrix product / elementwise
zip(a, b) / enumerate(v)
Iterate in pairs
v[v .> 0]
Select by boolean mask

Types & dispatch

struct P x::Float64; y::Float64 end
Immutable composite type
mutable struct C n::Int end
Mutable composite type
P(1.0, 2.0)
Construct a value
area(s::Circle) = pi * s.r^2
Method for one type
abstract type Shape end
Abstract supertype
struct Circle <: Shape ... end
Declare a subtype
Base.show(io::IO, p::P)
Custom display for a type
struct Box{T} v::T end
Parametric type
f(x::T) where T<:Number
Parametric method
methods(f)
See all methods
@which f(x)
Which method would run
f(a, b...) / f(v...)
Varargs / splat

Macros & tooling

@time f(x)
Time and allocation report
@btime f($x)
Accurate benchmark (BenchmarkTools)
Interpolate globals with $ to avoid skewed results.
@show x
Print expression and value
@code_warntype f(x)
Find type instabilities
Threads.@threads for ...
Parallel loop on threads
@testset "name" begin ... end
Group tests
@test <expr>
Assert in a test
@kwdef struct ... end
Struct with keyword constructor

Recipes

New project
mkdir myproj && cd myprojjulia --project=.# ] then: add DataFrames# julia> using DataFrames
Clone and run
git clone <url> && cd <repo>julia --project=. -e 'using Pkg; Pkg.instantiate()'julia --project=. src/main.jl
Script with an entry point
# main.jlfunction (@main)(args)    println("got $(length(args)) args")    return 0end
Threaded sum
# julia -t 4 sum.jlusing Base.Threadsv = rand(10^6)s = Atomic{Float64}(0)@threads for x in v    atomic_add!(s, x)end

Help

?<name>
Docs for a function or type