Skip to content

Julia Spickzettel

Julia ist eine hochentwickelte, performante dynamische Sprache für technisches Rechnen.

01

Grundlagen

Hello World

println ergänzt einen Zeilenumbruch, print nicht

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

Kommentare

#= =# für mehrzeilige Kommentare

julia
# Single-line comment

#=
  Multi-line
  comment
=#

# Docstring
"""docstring"""

REPL

ans speichert das vorherige Ergebnis

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

String-Interpolation

$ für Variablen, $(expression) für Ausdrücke

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

Verkettete Vergleiche

Julia unterstützt verkettete Vergleiche

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

Variablen

Variablen-Zuweisung

Unterstützt Unicode-Variablennamen

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

Konstanten

const deklariert eine globale Konstante

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

Typ-Annotationen

:: für Typ-Annotationen

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

Mehrfach-Zuweisung

Unterstützt Mehrfach-Zuweisung

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

Typen

Grundlegende Typen

typeof liefert den Typ

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

Typkonvertierung

Typnamen als Konvertierungsfunktion nutzen

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

Abstrakte Typen

abstract type definiert einen abstrakten Typ

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

Structs

struct ist unveränderlich

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

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

Veränderliche Structs

mutable struct erlaubt Feldänderungen

julia
mutable struct Counter
  count::Int
end

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

Parametrische Typen

T ist ein Typ-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

Funktions-Overloading

Julia-Kernfeature: 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"

Parametrische Methoden

where legt Typ-Parameter fest

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

# Works for all types T

Fallback-Methoden

Eine Methode ohne Typ-Annotationen wirkt als Default

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

# No type annotation, matches all arguments

Methoden-Mehrdeutigkeit

Achtung: Methoden-Mehrdeutigkeit vermeiden

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

Funktionen

Funktionsdefinition

return ist optional; zurückgegeben wird der letzte Ausdruck

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

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

Anonyme Funktionen

-> definiert eine anonyme Funktion

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

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

Mehrere Rückgabewerte

Gibt für mehrere Werte ein Tupel zurück

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

q, r = divrem2(10, 3)

Keyword-Argumente

Nach ; folgen Keyword-Argumente

julia
function plot(x, y; style="line", color="blue")
  # style and color are keyword arguments
end

plot(1:10, 1:10, color="red")

Variadische Argumente

... sammelt variadische Argumente

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

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

do-Block

do-Block übergibt eine anonyme Funktion

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

Kontrollfluss

if-elseif-else

Bedingter Ausdruck

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

Ternary-Operator

Ternary-Syntax: condition ? true_value : false_value

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

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

for-Schleife

for in Iteration

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

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

while-Schleife

while-Schleife

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

break und continue

&& Kurzschlussauswertung für Bedingungen

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

Arrays

Arrays erzeugen

Arrays sind 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-Indizierung

Indizes beginnen bei 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-Operationen

!-Suffix bedeutet in-place-Änderung

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

Ähnlich einer 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 für Broadcasting

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

Tupel

Tupel

Tupel sind unveränderlich

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

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

Destrukturierung

Tupel-Destrukturierungszuweisung

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

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

Dictionaries

Dictionaries erzeugen

Dict erzeugt ein dictionary

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

Zugriff und Änderung

[] für Zugriff und Änderung

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

Iteration

Über Key-Value-Paare iterieren

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

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

Dictionary-Operationen

Häufige Dictionary-Funktionen

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-Grundlagen

String-Indizes können nicht-lückenlos sein (UTF-8)

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

String-Operationen

Häufige String-Funktionen

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

Finden und Ersetzen

Finden und Ersetzen

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

Splitten und Zusammenfügen

split und join

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

Mathematische Funktionen

Grundmathematik

Eingebaute mathematische Funktionen

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

Trigonometrische Funktionen

In Radiant

julia
sin(π/2)   # 1.0
cos(0)     # 1.0
tan(π/4)  # 1.0
asin(1)   # 1.5707... (π/2)

Logarithmus und Exponential

log ist der natürliche Logarithmus

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

Sonderwerte

Mathematische Konstanten und Sonderwerte

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

Lineare Algebra

Matrix-Operationen

LinearAlgebra-Standardbibliothek

julia
using LinearAlgebra

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

Matrix-Zerlegung

Verschiedene Matrix-Zerlegungen

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

Vektor-Operationen

Vektor-Operationen

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

Statistik

Grundlegende Statistik

Statistics-Standardbibliothek

julia
using Statistics

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

Quantile

Quantilberechnung

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

Korrelation und Kovarianz

Korrelationskoeffizient und Kovarianz

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

Plotten

Grundlegendes Plotten

Plots.jl ist die Haupt-Plotbibliothek

julia
using Plots

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

Scatter-Plot

scatter zeichnet einen scatter plot

julia
using Plots

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

Subplots

layout steuert das Subplot-Layout

julia
using Plots

p1 = plot(1:10, 1:10)
p2 = plot(1:10, (1:10).^2)
plot(p1, p2, layout=(2, 1))

Bild speichern

savefig speichert das Bild

julia
using Plots

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

DataFrames

DataFrame erzeugen

DataFrames.jl ähnelt pandas

julia
using DataFrames

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

Auf Daten zugreifen

Zeilen- und Spaltenzugriff

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

Filtern und Sortieren

Filtern und Sortieren

julia
using DataFrames

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

Gruppieren und Aggregieren

groupby + combine für gruppierte Aggregation

julia
using DataFrames, Statistics

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

Datei-I/O

Text lesen und schreiben

open mit do-Block schließt die Datei automatisch

julia
# Write
open("output.txt", "w") do f
  write(f, "Hello World")
end

# Read
content = read("input.txt", String)

Zeile für Zeile lesen

eachline iteriert Zeile für Zeile

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

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

CSV-Dateien

CSV.jl behandelt CSV-Dateien

julia
using CSV, DataFrames

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

JSON-Dateien

JSON.jl behandelt JSON

julia
using JSON

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

Module

Modul definieren

export deklariert die öffentliche Schnittstelle

julia
module MyModule

export greet, add

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

end  # module

Modul importieren

Unterschied zwischen using und import

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

Standard-Module

Module der Standardbibliothek

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

Macros

Macro definieren

Macros arbeiten zur Kompilierzeit auf dem AST

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

@sayhi "Alice"  # Hi, Alice

Ausdruck-Quoting

:() erzeugt ein Ausdrucks-Objekt

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

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

Häufige Macros

Eingebaute häufige 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

Metaprogrammierung

Ausdruck-Konstruktion

Expr konstruiert einen AST

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

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

Code-Generierung

Loop zur Codegenerierung

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

f(+, 1, 2)  # 3

Macro-Hygiene

Macro-Hygiene vermeidet Variablenkonflikte

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

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

Paralleles Rechnen

Multi-Threading

@threads-macro für parallele Loops

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

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

Verteiltes Rechnen

Distributed-Standardbibliothek

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

@everywhere function work(x)
  x ^ 2
end

pmap(work, 1:100)  # parallel map

Remote Call

Asynchroner remote call

julia
using Distributed

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

# @spawnat executes on a specified process
21

Coroutines

Task

Task ist Julia's Coroutine

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

schedule(t)
wait(t)

Channel

Channel zur Kommunikation zwischen Coroutines

julia
ch = Channel(32)

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

Producer-Consumer

Coroutines implementieren 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

Ausnahmebehandlung

try-catch

try-catch-finally-Block

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

Ausnahme werfen

throw wirft ein Ausnahme-Objekt

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

Eigene Ausnahme

Vom Exception-Typ erben

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

Reguläre Ausdrücke

r"" erzeugt einen regex

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

Match

match gibt das Match-Ergebnis zurück

julia
m = match(r"(\w+)@(\w+)", "user@host")
m.match   # "user@host"
m.captures  # ["user", "host"]
m[1]      # "user"

Alle finden

eachmatch iteriert über alle Treffer

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

Ersetzen

replace unterstützt regex

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

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

DateTime

Datum erzeugen

Dates-Standardbibliothek

julia
using Dates

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

Formatierung

Formatieren und Parsen

julia
using Dates

dt = now()
Dates.format(dt, "yyyy-mm-dd HH:MM:SS")
Date("2024-01-15", "yyyy-mm-dd")

Datums-Arithmetik

Zeitintervall-Typen

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

Packages installieren

Pkg.add installiert packages

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

Package-Verwaltung

Häufige Pkg-Befehle

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

Umgebungen

Verwaltung der Projekt-Umgebung

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

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

Pkg-Manager

REPL-Pkg-Modus

] schaltet in den Pkg-REPL-Modus

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

Package erzeugen

generate erzeugt ein Package-Gerüst

julia
pkg> generate MyPackage

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

Entwicklungsmodus

dev installiert im Entwicklungsmodus

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

Interoperabilität

C aufrufen

ccall ruft C-Funktionen auf

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

Python aufrufen

PyCall.jl ruft Python auf

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

R aufrufen

RCall.jl ruft R auf

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

GPU-Rechnen

CUDA-Arrays

CUDA.jl unterstützt NVIDIA-GPUs

julia
using CUDA

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

GPU-Kernel

@cuda startet einen 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 unterstützt AMD-GPUs

julia
using AMDGPU

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

Was this helpful?