Collections
9.1 Tuples (immutable, fixed size, heterogeneous)
t = (1, "two", 3.0)
t[2] # "two"
length(t)
a, b, c = t # destructuring
first, rest... = (1, 2, 3) # rest = (2, 3) (Julia 1.6+ slurping)
typeof(t) # Tuple{Int64, String, Float64}9.2 Named tuples
p = (name="Ann", age=30)
p.name, p[:age], p[1]
keys(p), values(p)
merge(p, (age=31, city="Oslo"))
(; name, age) = p # property destructuring (1.7+)9.3 Dictionaries
d = Dict("a" => 1, "b" => 2)
d["c"] = 3
d["a"] # 1
get(d, "z", 0) # default
get!(d, "z", 0) # insert default if missing
haskey(d, "b"), "b" in keys(d)
delete!(d, "a"); pop!(d, "b")
keys(d), values(d), pairs(d)
for (k, v) in d; println(k, " => ", v); end
Dict(x => x^2 for x in 1:3) # comprehension
merge(d, Dict("y" => 9)); mergewith(+, d1, d2)
d2 = Dict{Symbol, Vector{Int}}()
sort(collect(d), by=last, rev=true)
using OrderedCollections: OrderedDict # insertion-ordered dict (package)9.4 Sets
s = Set([1, 2, 3, 3])
push!(s, 4); delete!(s, 1)
2 in s, 2 ∈ s
union(s, Set([9])), intersect(s, Set([2, 3])), setdiff(s, Set([2])), symdiff(a, b)
issubset(Set([2]), s), Set([2]) ⊆ s
unique([1, 1, 2]), allunique([1, 2])9.5 Ranges (lazy)
r = 1:10 # UnitRange — no memory allocated
1:2:9 # step range
range(0, 1, length=5) # 0.0:0.25:1.0
range(1, step=3, length=4)
LinRange(0, 1, 5)
collect(1:5) # materialize into a Vector
reverse(1:5), length(1:2:9), step(1:2:9), first(r), last(r)
'a':'e'9.6 Pairs & other structures
p = :a => 1; p.first, p.second
using DataStructures # Deque, Stack, Queue, PriorityQueue, DefaultDict, Accumulator, SortedDict...🧪 Part I Exercises
Write fizzbuzz(n) returning a vector of strings.
Write is_palindrome(s) that ignores case, spaces, and punctuation (Unicode-safe).
Compute the sum of all multiples of 3 or 5 below 1000 in one line with a generator.
Write word_count(text) returning a Dict{String,Int}, then print the top 5 words.
Write collatz(n) returning the sequence as a vector; find the start below 10 000 with the longest chain.
Implement my_map(f, v) and my_filter(p, v) using loops and push!.
Write a function with keyword arguments temperature(value; from=:C, to=:F).
Create a closure-based make_accumulator(start) returning a function that adds to a running total.
Use a do block to write and then read back a text file.
Represent a person as a named tuple; sort a vector of such tuples by age, then by name.