ANN: new package Reconstructables.jl for easier "modifications" of immutable structs

Hi, let me announce a beta package Reconstructables.jl:
https://github.com/tkf/Reconstructables.jl

Reconstructables.jl provides helper functions and macros to work with immutable structs in Julia. For example, using @recon macro, you can reconstruct a new struct with the nested field .x.y.z modified from the one in old by:

new = @recon old.x.y.z = 3

It works even when old, x and y are all immutable, provided that their they have keyword-only constructor. To generate keyword-only constructor, it also provides another macro @add_kwonly. For example,

struct A
    x
    y
    @add_kwonly A(x, y=2) = new(x, y)
end

expands to:

struct A
    x
    y
    A(x, y) = new(x, y)
    A(; x = throw(UndefKeywordError(:x)), y=2) = new(x, y)
end

Note that @recon and @add_kwonly are independent tools (in some sense). For example, @recon also works nicely with @with_kw from Parameters.jl. You may want to use @add_kwonly instead of @with_kw if you need to do something inside the inner constructor, like handling type parameters.

See more details in README.

I just sent a PR to METADATA.jl so if you want to try it out right now, use: It’s now in METADATA. You can install it by:

Pkg.add("Reconstructables")

A bit of history: this package is a spin-off from a PR in JuliaDiffEq/DiffEqBase.jl where we tried to solve a similar problem. I wrote @add_kwonly for DiffEqBase.jl and then @ChrisRackauckas suggested to make a package out of it since it may be useful elsewhere (Thanks!). But I thought one macro is not enough for a package so I wrote @recon :slight_smile:

10 Likes