Schnell wie C, einfach wie Python
Ausführen: Datei hallo.jl speichern und mit julia hallo.jl ausführen (Julia von julialang.org). Mit julia allein startest du die interaktive Konsole.
println, print, @show; Interpolation mit $name und $(ausdruck)/ ergibt Float, ÷ oder div Ganzzahldivision, ^ Potenz, // Brücheπ, ≤)? Hilfe, ] Paketmodusjulia # interaktive Konsole (REPL), beenden mit exit()
julia hallo.jl # Datei ausführen
julia -e 'println(1 + 2)'
julia --project=. skript.jl # mit Projektumgebungtypeof, <:, isa); Konvertierung mit Int(x), parse(Int, "42")* verkettet, ^ wiederholt, $ interpoliert; @printf formatiertif/elseif/else/end, ?:, &&, ||; for ... in, while, break, continue[ausdruck for x in ... if ...] und Generatoren1:n ist ein Bereich, Indizes beginnen bei 1println(typeof(42), " ", typeof(3.14), " ", typeof("Text"), " ", typeof('c'))
println(typeof(true), " ", typeof(nothing), " ", typeof(1:5), " ", typeof([1, 2]))
println(typeof(1 // 2), " ", typeof(2 + 3im), " ", typeof(:symbol), " ", typeof((1, "a")))
println(Int64 <: Integer, " ", Integer <: Real, " ", Float64 <: Real, " ", String <: Number)
println(supertype(Int64), " ", supertype(Real))
println(sizeof(Int64), " ", sizeof(Int8), " ", sizeof(Float32))
println(Int8(100) + Int8(100)) # Überlauf (wrap-around)
println(Int(3.0), " ", Float64(3), " ", UInt8(200), " ", Char(65), " ", Int('A'))
println(parse(Int, "42") + 1, " ", parse(Float64, "2.5"), " ", tryparse(Int, "x"))
println(string(42) * "!", " ", repr("text"))
x::Int = 5 # Typannotation (global)
println(isa(x, Int), " ", x isa Number)
println(convert(Float64, 3), " ", promote(1, 2.5), " ", 1 + 2.5)function ... end oder f(x) = ...; mehrere Rückgabewerte als Tupel; ... sammelt/entpacktf.(v), v .+ w! verändern ihre Argumente (Konvention)x::Int) steuern die Methodenauswahlfunction addiere(a, b)
return a + b
end
quadrat(x) = x^2 # Kurzform
gruss(name = "Welt"; anrede = "Hallo") = "$anrede, $(name)!" # Standardwert und Schlüsselwort-Argument
function minmax(v)
return minimum(v), maximum(v) # mehrere Werte (Tupel)
end
summe(zahlen...) = sum(zahlen) # beliebig viele Argumente
println(addiere(2, 3), " ", quadrat(7))
println(gruss(), " ", gruss("Mia"), " ", gruss("Tom"; anrede = "Hi"))
lo, hi = minmax([4, 8, 15, 16, 23, 42])
println(lo, " ", hi)
println(summe(1, 2, 3, 4), " ", summe([5, 6]...))
# Anonyme Funktionen und Höhere Funktionen
println(map(x -> x * 2, [1, 2, 3]))
println(filter(iseven, 1:10))
println(reduce(+, 1:5), " ", foldl(-, 1:4), " ", sum(abs2, [3, 4]))
println((x -> x + 1)(41))
println(map(sqrt, [4, 9, 16]), " ", sqrt.([4, 9, 16])) # Punktschreibweise: elementweise
println([1, 2, 3] .+ 10, " ", [1, 2, 3] .* [4, 5, 6], " ", (1:3) .^ 2)
println((sin ∘ cos)(0.0)) # Funktionskomposition
println([1, 2, 3] |> sum |> sqrt) # Pipe
# Funktionen mit "!" verändern ihre Argumente
liste = [3, 1, 2]
sort!(liste)
push!(liste, 10)
println(liste)
# Rekursion
fakultaet(n) = n <= 1 ? 1 : n * fakultaet(n - 1)
fib(n) = n < 2 ? n : fib(n - 1) + fib(n - 2)
println(fakultaet(10), " ", fakultaet(big(25)), " ", [fib(i) for i in 0:10])
# Closure
function zaehler()
n = 0
return () -> (n += 1)
end
z = zaehler()
z(); z()
println(z())Vector/Matrix: Indizes ab 1; push!, pop!, sort, sum, findall, Slicing v[2:3][1 2; 3 4], A * B, A', A \ b; LinearAlgebra für det, inv, eigvals(name = "Mia"), Entpacken a, b = tDict("a" => 1), get, haskey, delete!; Set für Mengenv = [5, 3, 9, 1]
println(v, " ", length(v), " ", v[1], " ", v[end], " ", v[2:3], " ", v[[1, 4]])
push!(v, 7); pushfirst!(v, 0)
println(v)
letztes = pop!(v); erstes = popfirst!(v)
println(letztes, " ", erstes, " ", v)
append!(v, [20, 30]); insert!(v, 2, 99); deleteat!(v, 2)
println(v)
println(sort(v), " ", sort(v, rev = true), " ", reverse(v), " ", sortperm(v))
println(sum(v), " ", prod([1, 2, 3, 4]), " ", maximum(v), " ", minimum(v), " ", extrema(v))
println(findall(>(5), v), " ", findfirst(==(9), v), " ", v[v .> 5], " ", count(iseven, v))
println(any(>(25), v), " ", all(>(0), v), " ", 9 in v, " ", unique([1, 2, 2, 3, 1]))
println(zeros(3), " ", ones(Int, 2), " ", fill(7, 3), " ", collect(1:2:9), " ", range(0, 1, length = 5))
println(cumsum(1:5), " ", diff([1, 4, 9]), " ", vcat([1, 2], [3]), " ", [1, 2] == [1, 2])
println(first(v, 2), " ", last(v, 2), " ", length(similar(v)), " ", eltype(v), " ", typeof([1, 2.5, 3]))
println(join(v[1:3], ", "), " ", string.(1:3), " ", isempty([]), " ", Int[])struct (unveränderlich) und mutable struct; abstrakte Typen bilden Hierarchiennew(...), parametrische Typen Paar{A, B}try/catch/finally, throw, rethrow(), tryparsemodule ... end, export, using, importstruct Punkt # unveränderlich (immutable)
x::Float64
y::Float64
end
mutable struct Konto # veränderlich
inhaber::String
stand::Float64
end
abstract type Form end
struct Kreis <: Form; r::Float64 end
struct Rechteck <: Form; b::Float64; h::Float64 end
flaeche(k::Kreis) = π * k.r^2
flaeche(r::Rechteck) = r.b * r.h
umfang(k::Kreis) = 2π * k.r
umfang(r::Rechteck) = 2 * (r.b + r.h)
p = Punkt(3, 4)
println(p, " ", p.x, " ", typeof(p), " ", fieldnames(Punkt))
k = Konto("Mia", 100.0)
k.stand += 50
println(k.inhaber, " ", k.stand, " ", ismutable(k), " ", ismutable(p))
formen = [Kreis(1.0), Rechteck(3.0, 4.0), Kreis(2.5)]
for f in formen
println(typeof(f), ": Fläche ", round(flaeche(f), digits = 2), ", Umfang ", round(umfang(f), digits = 2))
end
println(sum(flaeche, formen) |> x -> round(x, digits = 3))
println(sort(formen, by = flaeche) .|> typeof)
# Konstruktoren mit Prüfung und Standardwerten
struct Person
name::String
alter::Int
function Person(name, alter)
alter < 0 && throw(ArgumentError("Alter darf nicht negativ sein"))
new(name, alter)
end
end
Person(name) = Person(name, 18)
println(Person("Tom"), " ", Person("Zoe", 31).alter)
try
Person("Ben", -5)
catch e
println(typeof(e), ": ", e.msg)
end
# Parametrische Typen
struct Paar{A, B}
erstes::A
zweites::B
end
println(Paar(1, "eins"), " ", typeof(Paar(1.5, :x)))
using Printf
Base.show(io::IO, p::Punkt) = @printf(io, "Punkt(%.1f, %.1f)", p.x, p.y)
println(p, " ", [Punkt(1, 2), Punkt(3, 4)])@., @views@time, BenchmarkTools @btime, analysieren mit @code_warntypeThreads.@spawn, @threads, Channel, Distributed, GPUfunction summe_schleife(v)
s = 0.0
for x in v
s += x
end
return s
end
function summe_instabil(v)
s = 0 # Int – wird beim ersten += zu Float64: Typ wechselt!
for x in v
s += x
end
return s
end
v = rand(1_000_000)
println(isapprox(summe_schleife(v), sum(v)))
println(isapprox(summe_instabil(v), sum(v)))
t = @elapsed for _ in 1:20 summe_schleife(v) end
println(t < 5.0 ? "schnell genug" : "langsam")
# Typinformation prüfen
println(Base.return_types(summe_schleife, (Vector{Float64},))) # Julia leitet Float64 ab
println(Base.return_types(summe_instabil, (Vector{Float64},))) # Union{Float64, Int64}: instabil
println(typeof(summe_schleife([1.0, 2.0])), " ", typeof(summe_instabil([1.0, 2.0])), " ", typeof(summe_instabil([1, 2])))Pkg verwaltet Pakete pro Projekt (Project.toml, Manifest.toml)MersenneTwister(seed)PythonCall.jl) und C (ccall)# In der REPL: ] drücken, dann
# pkg> activate . Projektumgebung aktivieren
# pkg> add Plots DataFrames CSV
# pkg> status
# pkg> update
# pkg> test
# Oder im Code:
# using Pkg; Pkg.add("DataFrames")x = 5 Variable const PI2 = 2π Konstante
function f(a, b = 1; k = 2) ... end f(x) = x^2 Funktionen
if ... elseif ... else ... end cond ? a : b a && b a || b
for i in 1:10 ... end while ... end break continue
[x^2 for x in 1:5 if isodd(x)] Dict(k => v for ...) (x for x in 1:5)
struct P; x::Int end mutable struct abstract type T end
module M ... end using Statistics import Base: +
try ... catch e ... finally ... end throw(ArgumentError("..."))