Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 40 ยท Projects

Project: A Small Generic Package

Build a small Julia package from scratch: parametric types, multiple dispatch, constructors, a test suite, docstrings and docs, and how to share it.

A Julia package is a folder with a Project.toml, a src/ directory and (ideally) tests and documentation. In this project you will write a small but real package called Intervals: a type for a range of values [lo, hi] with arithmetic that follows the rules of interval math. For example, if x is somewhere between 1 and 2 and y is somewhere between 3 and 4, then x + y is somewhere between 4 and 6.

The project pulls together almost everything from the course: parametric types, constructors, multiple dispatch, modules, environments and tests. Julia is not installed on this site, so the package code is read-only. Two Python stand-ins run here: a port of the type with a hand-made test run, and a small test reporter that shows how a failing test is summarized.

The package at a glance

Layout Project.toml, src, test, docs.
One generic type Interval{T} works for any real number type.
Dispatch One method per case, one name for all.
Tests and docs A test suite and doctested examples.
1 / 2

The layout

You can create a skeleton from the package manager. From the Pkg mode of the REPL (press ]):

JULIA
pkg> generate Intervals

This makes the folder Intervals/ with Project.toml and src/Intervals.jl. For a fuller template that adds tests, a CI file and documentation, the PkgTemplates.jl package builds it from a few options. A finished package looks like this:

Text
Intervals/
โ”œโ”€โ”€ Project.toml          # name, uuid, version, [deps], [compat]
โ”œโ”€โ”€ src/
โ”‚   โ””โ”€โ”€ Intervals.jl      # module Intervals ... end
โ”œโ”€โ”€ test/
โ”‚   โ”œโ”€โ”€ Project.toml      # test-only dependencies
โ”‚   โ””โ”€โ”€ runtests.jl
โ””โ”€โ”€ docs/
    โ”œโ”€โ”€ Project.toml
    โ”œโ”€โ”€ make.jl
    โ””โ”€โ”€ src/index.md

The Project.toml identifies the package. generate fills in a uuid, a name and your authors:

TOML
name = "Intervals"
uuid = "..."            # created for you, never reuse another package's
version = "0.1.0"

[compat]
julia = "1.10"

To work on it, activate the folder (activate .) and load it with using Intervals. With Revise loaded first, edits in src/ take effect in the running REPL (Debugging and Profiling).

The type

An interval has a lower and an upper end of the same real type T. A custom inner constructor enforces the one rule that makes an interval valid: lo โ‰ค hi. Outer constructors then add convenience: Interval(1, 2) infers T, and mixed arguments such as Interval(1, 2.5) are promoted to a common type.

JULIA
module Intervals

export Interval, width, center, overlaps, hull

"""
    Interval(lo, hi)

A closed interval ``[lo, hi]`` over a real number type. Arguments of
different types are promoted to a common type.
"""
struct Interval{T<:Real}
    lo::T
    hi::T

    function Interval{T}(lo, hi) where {T<:Real}
        lo <= hi || throw(ArgumentError("lo must not exceed hi, got $lo > $hi"))
        return new{T}(lo, hi)
    end
end

Interval(lo::T, hi::T) where {T<:Real} = Interval{T}(lo, hi)
Interval(lo::Real, hi::Real) = Interval(promote(lo, hi)...)

Base.show(io::IO, a::Interval) = print(io, "[", a.lo, ", ", a.hi, "]")

The type parameter T means one definition serves Interval{Int}, Interval{Float64}, Interval{Rational{Int}} and even Interval{BigFloat}. The compiler generates specialized code for each, so there is no speed penalty for being generic.

The methods

Each operation is a method on Interval. Addition and subtraction work on the ends. Multiplication needs care, because a negative number flips the order: the extremes of the product are among the four products of the ends.

JULIA
width(a::Interval)  = a.hi - a.lo
center(a::Interval) = (a.lo + a.hi) / 2
overlaps(a::Interval, b::Interval) = a.lo <= b.hi && b.lo <= a.hi
hull(a::Interval, b::Interval) = Interval(min(a.lo, b.lo), max(a.hi, b.hi))

Base.in(x::Real, a::Interval) = a.lo <= x <= a.hi

Base.:+(a::Interval, b::Interval) = Interval(a.lo + b.lo, a.hi + b.hi)
Base.:-(a::Interval, b::Interval) = Interval(a.lo - b.hi, a.hi - b.lo)

function Base.:*(a::Interval, b::Interval)
    products = (a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi)
    return Interval(minimum(products), maximum(products))
end

# mixing an interval with a plain number: shift it
Base.:+(a::Interval, x::Real) = Interval(a.lo + x, a.hi + x)
Base.:+(x::Real, a::Interval) = a + x

# lets sum([...]) and friends start from an additive identity
Base.zero(::Type{Interval{T}}) where {T} = Interval(zero(T), zero(T))
Base.zero(a::Interval) = zero(typeof(a))

end # module

Notice what dispatch is doing. + has four methods now in your package alongside the hundreds in Base: interval plus interval, interval plus number, number plus interval, and the built-in ones. Extending Base.:+ for your own type is exactly what the multiple dispatch lesson recommends, and it is not type piracy because Interval is yours. Because + and zero work, sum works with no extra code:

JULIA
using Intervals

a = Interval(1, 2)
b = Interval(3, 4)

a + b                         # [4, 6]
a * Interval(-1, 3)           # [-2, 6]
0.5 in Interval(0, 1)         # true
sum([a, b, Interval(0, 1)])   # [4, 7]
width(a + b)                  # 2
Interval(3, 1)                # ERROR: ArgumentError: lo must not exceed hi, got 3 > 1

The tests

Tests live in test/runtests.jl and use the Test standard library. Group related checks in @testset blocks, and test both success and failure paths:

JULIA
using Intervals
using Test

@testset "Intervals" begin
    @testset "construction" begin
        @test Interval(1, 3) isa Interval{Int}
        @test Interval(1, 2.5) isa Interval{Float64}
        @test_throws ArgumentError Interval(3, 1)
    end

    @testset "arithmetic" begin
        @test Interval(1, 2) + Interval(3, 4) == Interval(4, 6)
        @test Interval(1, 2) - Interval(0, 1) == Interval(0, 2)
        @test Interval(1, 2) * Interval(-1, 3) == Interval(-2, 6)
        @test 1 + Interval(1, 2) == Interval(2, 3)
        @test sum([Interval(1, 2), Interval(3, 4)]) == Interval(4, 6)
    end

    @testset "queries" begin
        @test 0.5 in Interval(0, 1)
        @test !(2 in Interval(0, 1))
        @test overlaps(Interval(0, 2), Interval(1, 3))
        @test !overlaps(Interval(0, 1), Interval(2, 3))
        @test width(hull(Interval(0, 1), Interval(4, 5))) == 5
    end
end

Run them in a clean, isolated environment with pkg> test. Test the rules of the domain, not only examples: for intervals, a good extra test checks that for random numbers x in a and y in b, the sum x + y always lies in a + b.

For continuous integration, a GitHub Actions workflow with julia-actions/setup-julia and julia-actions/julia-runtest runs the same tests on several Julia versions and operating systems every time you push.

The documentation

Docstrings in the source become the reference documentation. A jldoctest block inside a docstring is a test too: Documenter.jl runs the example and compares the output with what you wrote, so examples cannot silently go stale. Here is how an example is written inside the docstring of Interval, using a fence marked jldoctest (shown with an outer four-backtick fence so the inner one is visible):

JULIA
"""
    Interval(lo, hi)

A closed interval over a real number type.

# Examples
```jldoctest
julia> Interval(1, 3)
[1, 3]

julia> Interval(1, 2.5)
[1.0, 2.5]
```
"""

A minimal docs/make.jl:

JULIA
using Documenter, Intervals

DocMeta.setdocmeta!(Intervals, :DocTestSetup, :(using Intervals); recursive = true)

makedocs(
    sitename = "Intervals.jl",
    modules  = [Intervals],
    pages    = ["Home" => "index.md"],
)

And docs/src/index.md pulls in the docstrings with a block:

Text
# Intervals.jl

```@docs
Interval
width
overlaps
```

Sharing it

  1. Push the package to a Git repository (the convention is a repo named Intervals.jl).
  2. Pick a version. Julia packages follow semantic versioning: 0.1.0 while the API is changing, 1.0.0 once it is stable, and a major bump for breaking changes.
  3. List version bounds for each dependency in [compat], otherwise registration is refused.
  4. Register the version in the General registry with the Registrator bot, then let TagBot tag the release.
  5. Users install it with pkg> add Intervals.

You do not have to register a package to use it: pkg> add https://github.com/you/Intervals.jl installs straight from a Git URL, and pkg> develop ./Intervals links a local folder, which is what you want while you work on it.

Python stand-in: the type and a test run

This port keeps the design. Python has no parametric types or multiple dispatch, so a method that accepts either an interval or a plain number checks the type of its argument inside. The check function plays the role of @test and the final count resembles a testset summary:

Python Interval arithmetic with tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python stand-in: how a testset reports failures

Julia's @testset does not stop at the first failure: it runs every test, then prints a table of passes, failures and errors with the line of each problem. This reporter has the same behavior. One check is wrong on purpose, so you can see the failure report:

Python A testset summary with a failure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The failing equality is the reason Julia has @test a โ‰ˆ b (the isapprox operator) for floating-point results, as covered in Testing with Test.jl.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does Interval{T<:Real} use an inner constructor?

    An inner constructor is the only place new can be called, so every Interval passes through the validation.
  2. 2. Why is Base.:+(a::Interval, b::Interval) not type piracy?

    Piracy means adding a method to someone else's function for only someone else's types. Interval is your own type.
  3. 3. What is the benefit of jldoctest blocks in docstrings?

    The example output is compared with the real output when the docs are built.
  4. 4. Which version style marks a package whose public API is still changing?

    Under semantic versioning, 0.x releases may break compatibility between minor versions. 1.0.0 promises a stable API.
  5. 5. Why does sum([a, b]) work for Interval without a special sum method?

    Generic functions are written in terms of other functions. Once + and zero exist for your type, sum works.

Summary

  • A package is a folder with Project.toml, src/, test/ and optionally docs/; generate or PkgTemplates.jl creates it.
  • A parametric struct with an inner constructor enforces invariants once; outer constructors add convenience such as promotion.
  • Extend Base functions for your own type (+, show, in, zero) and generic code like sum works automatically.
  • Test with @testset, @test and @test_throws; run pkg> test in an isolated environment; use CI for several Julia versions.
  • Docstrings with jldoctest examples become tested documentation; register with Registrator and tag releases with TagBot.

Next: simulate randomness in Project: Monte Carlo Estimation.