Julia Interfaces
Julia has no interface keyword. Instead, an interface is an informal agreement: "if your type defines these methods, then all of those generic functions will work with it". Implementing a handful of methods plugs your type into for loops, collect, sum, indexing, broadcasting and more.
The iteration interface
To make a type usable in a for loop, define Base.iterate:
| Method | Returns |
|---|---|
iterate(x) |
(first_item, state) or nothing if empty |
iterate(x, state) |
(next_item, new_state) or nothing when done |
length(x) (optional) |
number of items, used by collect |
eltype(::Type{T}) (optional) |
element type, so collect builds a typed array |
struct Countdown
from::Int
end
Base.iterate(c::Countdown, state=c.from) = state < 1 ? nothing : (state, state - 1)
Base.length(c::Countdown) = c.from
Base.eltype(::Type{Countdown}) = Int
for n in Countdown(3)
print(n, "… ")
end
println("go!")
println(collect(Countdown(5)))
println(sum(Countdown(10)), " ", maximum(Countdown(4)))
println([n^2 for n in Countdown(3)])
println(7 in Countdown(9), " ", 0 in Countdown(9))3… 2… 1… go!
[5, 4, 3, 2, 1]
55 4
[9, 4, 1]
true false
Under the hood, for n in c is rewritten into a while loop that calls iterate until it returns nothing. Every function built on iteration — sum, maximum, in, comprehensions, zip, enumerate — now works with Countdown for free.
A lazy infinite iterator
Iterators don't need to store their items. This one produces Fibonacci numbers forever; Iterators.take limits it:
struct Fibs end
Base.iterate(::Fibs, (a, b)=(1, 1)) = (a, (b, a + b))
Base.IteratorSize(::Type{Fibs}) = Base.IsInfinite()
Base.eltype(::Type{Fibs}) = Int
println(collect(Iterators.take(Fibs(), 10)))
for (i, f) in enumerate(Fibs())
f > 1000 && (println("first above 1000: F", i, " = ", f); break)
end[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
first above 1000: F17 = 1597
The state here is a tuple (a, b), destructured directly in the argument list. IteratorSize tells generic code not to ask for a length, and eltype lets collect build a Vector{Int} instead of a Vector{Any}.
The indexing interface
To support x[i] and x[i] = v, define getindex and setindex!. Adding firstindex/lastindex makes begin and end work:
struct Weekdays end
const NAMES = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
Base.getindex(::Weekdays, i::Int) = NAMES[mod1(i, 7)] # wraps around
Base.firstindex(::Weekdays) = 1
Base.lastindex(::Weekdays) = 7
w = Weekdays()
println(w[1], " ", w[end], " ", w[9], " ", w[0])
println([w[i] for i in 5:8])Mon Sun Tue Sun
["Fri", "Sat", "Sun", "Mon"]
The AbstractArray interface
The most powerful interface: subtype AbstractArray{T, N} and define just size and getindex. You get iteration, printing, slicing, broadcasting, sum, sort (to a copy), linear algebra and more.
struct Squares <: AbstractVector{Int}
n::Int
end
Base.size(s::Squares) = (s.n,)
Base.getindex(s::Squares, i::Int) = (checkbounds(s, i); i^2)
s = Squares(6)
println(s)
println(length(s), " ", sum(s), " ", s[end])
println(s[2:4])
println(s .+ 1)
println(reverse(s))
println(filter(iseven, s))[1, 4, 9, 16, 25, 36]
6 91 36
[4, 9, 16]
[2, 5, 10, 17, 26, 37]
[36, 25, 16, 9, 4, 1]
[4, 16, 36]
Squares(6) never stores any numbers — each element is computed when it's read — yet it behaves like a regular vector everywhere. checkbounds throws the usual BoundsError for invalid indices.
Other common interfaces
| To support | Define |
|---|---|
sorting, <, max |
Base.isless(a, b) |
== and use as a Dict key |
Base.:(==)(a, b) and Base.hash(x, h::UInt) |
| printing | Base.show(io::IO, x) |
sum of an empty collection |
Base.zero(::Type{T}) |
property access x.name |
Base.getproperty(x, s::Symbol) |
struct Version
major::Int
minor::Int
end
Base.isless(a::Version, b::Version) = (a.major, a.minor) < (b.major, b.minor)
Base.show(io::IO, v::Version) = print(io, "v", v.major, ".", v.minor)
releases = [Version(1, 10), Version(0, 7), Version(1, 2)]
println(sort(releases))
println(maximum(releases), " ", Version(1, 2) < Version(1, 10))Version[v0.7, v1.2, v1.10]
v1.10 true
Comparing tuples is lexicographic, so (1, 2) < (1, 10) is true — exactly what version numbers need.
Test yourself
What must Base.iterate return when there are no more items?
- false
- nothing
- an empty tuple
- it must throw StopIteration
Which two methods are the minimum needed for a subtype of AbstractVector?
- length and iterate
- size and getindex
- push! and pop!
- show and ==
Which method makes sort work for a custom type?
- Base.sort
- Base.isless
- Base.compare
- Base.order