Julia Sets
A set is a collection that holds each value only once. Adding a value that is already in the set changes nothing.
Duplicates collapse into one
The array below has four items, with 2 appearing twice. The set built from it holds only three values.
s = Set([1, 2, 2, 3])
println(length(s))in checks membership
The in operator reports whether a value is in the set. Here 2 is a member and 9 is not.
s = Set([1, 2, 3])
println(2 in s)
println(9 in s)push! adds a new value
push! adds 4 to the set below. The sorted list of members shows all four values.
s = Set([1, 2, 3])
push!(s, 4)
println(length(s))
println(sort(collect(s)))Example
a = Set([1, 2, 3])
b = Set([2, 3, 4])
println(sort(collect(union(a, b))))
println(sort(collect(intersect(a, b))))Key points
- Set: the function that builds a set from an array of values.
- Unique: a set keeps one copy of each value, so duplicates collapse into one.
- length: length(s) counts the different values the set holds.
- Membership: x in s reports whether the value x is in the set.
- push!: push!(s, 4) adds a value to the set.
- union and intersect: union joins two sets, and intersect keeps only the values found in both.
In this example, union combines both sets, giving 1, 2, 3, and 4 with no repeats. intersect keeps only the values that appear in both sets, which are 2 and 3. Both results are printed as sorted lists, because a set itself has no order.
Note
a set has no order, so print sort(collect(s)) when you need the members in order.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What is length(Set([5, 5, 5]))?