Typen
Julia hat ein reichhaltiges Typsystem. Jeder Wert hat einen Typ (typeof), und Typen bilden eine Hierarchie (Int64 <: Signed <: Integer <: Real <: Number).
println(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)Int64 Float64 String Char
Bool Nothing UnitRange{Int64} Vector{Int64}
Rational{Int64} Complex{Int64} Symbol Tuple{Int64, String}
true true true false
Signed Number
8 1 4
-56
3 3.0 200 A 65
43 2.5 nothing
42! "text"
true true
3.0 (1.0, 2.5) 3.5Strings und Zeichen
s = "Hallo Welt"
println(length(s), " ", s[1], " ", s[end], " ", s[1:5], " ", s[end-3:end])
println(uppercase(s), " ", lowercase(s), " ", titlecase("ein titel"))
println(replace(s, "Welt" => "Julia"), " ", occursin("Welt", s), " ", startswith(s, "Hal"))
println(split("a,b,,c", ","), " ", join(["x", "y", "z"], "-"))
println(strip(" getrimmt "), "|", lpad("7", 3, '0'), "|", rpad("ab", 5, '.'), "|")
println("ab" * "cd", " ", "x"^3, " ", reverse("abc"))
println(findfirst("l", s), " ", findall("l", s), " ", count("l", s))
println(collect("Häx"), " ", length("Häx"), " ", sizeof("Häx")) # Zeichen vs. Bytes
println(chomp("Zeile\n"), " ", isdigit('7'), " ", isletter('x'), " ", isuppercase('A'))
println("Tab:\t|", ' ', "Anführung: \"x\"", ' ', raw"kein $Ersatz")
println(string("a", 1, :b, 2.5), " ", repeat("-", 10))
println(sprint(show, "q"), " ", match(r"(\d+)-(\d+)", "tel 030-1234").captures)
println(eachmatch(r"\d+", "a1b22c333") |> collect .|> m -> m.match)
text = """
Mehrzeilig
mit Einrückung
"""
print(text)
using Printf
@printf("%5.2f | %-6s| %04d | %e\n", 3.14159, "ab", 42, 12345.678)
println(@sprintf("%x %o", 255, 8), " ", string(5, base = 2))10 H t Hallo Welt
HALLO WELT hallo welt Ein Titel
Hallo Julia true true
SubString{String}["a", "b", "", "c"] x-y-z
getrimmt|007|ab...|
abcd xxx cba
3:3 UnitRange{Int64}[3:3, 4:4, 9:9] 3
['H', 'ä', 'x'] 3 4
Zeile true true true
Tab: | Anführung: "x" kein $Ersatz
a1b2.5 ----------
"q" Union{Nothing, SubString{String}}["030", "1234"]
SubString{String}["1", "22", "333"]
Mehrzeilig
mit Einrückung
3.14 | ab | 0042 | 1.234568e+04
ff 10 101Strings sind unveränderlich und UTF-8-kodiert; s[i] indiziert Bytes, bei Sonderzeichen deshalb Vorsicht (nutze collect(s) oder eachindex). Zeichen schreibst du mit 'c', Texte mit "...".
Verzweigungen
punkte = 78
if punkte >= 90
println("sehr gut")
elseif punkte >= 75
println("gut")
else
println("weiter üben")
end
println(punkte >= 50 ? "bestanden" : "durchgefallen") # ternärer Operator
println(punkte > 50 && punkte < 100) # Kurzschluss-Und
punkte > 100 || println("nicht über 100") # Kurzschluss-Oder als Bedingung
nachricht = if punkte > 70 "stark" else "schwach" end # if ist ein Ausdruck
println(nachricht)
println(1 < 2 < 3, " ", !true, " ", xor(true, false), " ", true & false, " ", true | false)
println(isnothing(nothing), " ", something(nothing, 5), " ", ismissing(missing), " ", missing + 1)
println(in(3, [1, 2, 3]), " ", 3 in 1:5, " ", 3 ∈ [1, 2], " ", 4 ∉ [1, 2])gut bestanden true nicht über 100 stark true false true false true true 5 true missing true true false true
Schleifen
for i in 1:3
print(i, " ")
end
println()
for i in 10:-3:1 print(i, " ") end
println()
for (i, f) in enumerate(["rot", "grün", "blau"])
print(i, "=", f, " ")
end
println()
for c in "Julia" print(c, ".") end
println()
for (a, b) in zip(1:3, "xyz") print(a, b, " ") end
println()
for x in 1:2, y in 1:3 print("($x,$y)") end # verschachtelt in einer Zeile
println()
n = 3
while n > 0
print(n, " ")
global n -= 1 # global nötig im Skript-Scope
end
println()
for i in 1:10
i % 2 == 0 && continue
i > 7 && break
print(i, " ")
end
println()
println([x^2 for x in 1:5]) # Comprehension
println([x * y for x in 1:3, y in 1:3])
println([x for x in 1:20 if x % 3 == 0])
println(sum(x^2 for x in 1:10)) # Generator ohne Zwischenliste
println(sort(collect(Dict(k => length(k) for k in ["aa", "b", "ccc"])))) # Dict-Reihenfolge ist nicht festgelegt1 2 3 10 7 4 1 1=rot 2=grün 3=blau J.u.l.i.a. 1x 2y 3z (1,1)(1,2)(1,3)(2,1)(2,2)(2,3) 3 2 1 1 3 5 7 [1, 4, 9, 16, 25] [1 2 3; 2 4 6; 3 6 9] [3, 6, 9, 12, 15, 18] 385 ["aa" => 2, "b" => 1, "ccc" => 3]
Merke
- Typen bilden eine Hierarchie (
typeof,<:,isa); Konvertierung mitInt(x),parse(Int, "42") - Strings sind unveränderlich,
*verkettet,^wiederholt,$interpoliert;@printfformatiert if/elseif/else/end,?:,&&,||;for ... in,while,break,continue- Comprehensions
[ausdruck for x in ... if ...]und Generatoren 1:nist ein Bereich, Indizes beginnen bei 1
Aufgabe
Gib alle Zahlen von 1 bis 30 aus und ersetze Vielfache von 3 durch "Fizz", von 5 durch "Buzz".