Julia Cheat Sheet BW Clean
Julia Cheat Sheet BW Clean
Control Flow
# If-Else
if x > 0
println("Positive")
elseif x == 0
println("Zero")
else
println("Negative")
end
# Loops
for i in 1:5
println(i)
end
while x > 0
x -= 1
end
# Function Definition
function add(a, b)
return a + b
end
# One-liner
square(x) = x^2
# Anonymous Function
f = x -> x * 2
# Scope
let x = 5
println(x)
end
Collections
# Arrays
a = [1, 2, 3]
a[1] # Access first element
push!(a, 4) # Add element
Julia Cheat Sheet
# Tuples
t = (1, "hello", 3.0)
# Dictionaries
d = Dict("a" => 1, "b" => 2)
d["a"] # Get value
Julia Cheat Sheet
# Broadcasting (element-wise)
[1, 2, 3] .+ 1 # [2, 3, 4]
sin.([0, pi/2, pi]) # [0.0, 1.0, 0.0]
# List Comprehension
[x^2 for x in 1:5] # Squares
[(x, y) for x in 1:2, y in 1:2] # Pairs
# Using Modules
using Statistics, LinearAlgebra
# Install Packages
using Pkg
Pkg.add("Plots")
# Define Module
module MyUtils
export greet
greet() = println("Hi!")
end
# Useful Macros
@time sum(1:1000000)
@assert 2 + 2 == 4
# Strings
name = "Julia"
"Hello, $name!" # Interpolation
split("a,b,c", ",") # ["a", "b", "c"]
# File I/O
write("file.txt", "Data")
content = read("file.txt", String)
Performance Tips