Docstrings

Setfield.LensType
Lens

A Lens allows to access or replace deeply nested parts of complicated objects.

Example

julia> using Setfield

julia> struct T;a;b; end

julia> obj = T("AA", "BB")
T("AA", "BB")

julia> lens = @lens _.a
(@lens _.a)

julia> get(obj, lens)
"AA"

julia> set(obj, lens, 2)
T(2, "BB")

julia> obj
T("AA", "BB")

julia> modify(lowercase, obj, lens)
T("aa", "BB")

Interface

Concrete subtypes of Lens have to implement

  • set(obj, lens, val)
  • get(obj, lens)

These must be pure functions, that satisfy the three lens laws:

@assert get(set(obj, lens, val), lens) ≅ val
        # You get what you set.
@assert set(obj, lens, get(obj, lens)) ≅ obj
        # Setting what was already there changes nothing.
@assert set(set(obj, lens, val1), lens, val2) ≅ set(obj, lens, val2)
        # The last set wins.

Here is an appropriate notion of equality or an approximation of it. In most contexts this is simply ==. But in some contexts it might be ===, , isequal or something else instead. For instance == does not work in Float64 context, because get(set(obj, lens, NaN), lens) == NaN can never hold. Instead isequal or ≅(x::Float64, y::Float64) = isequal(x,y) | x ≈ y are possible alternatives.

See also @lens, set, get, modify.

source
Base.getFunction
get(obj, l::Lens)

Access a deeply nested part of obj. See also Lens.

source
Setfield.setFunction
set(obj, l::Lens, val)

Replace a deeply nested part of obj by val. See also Lens.

source
Setfield.@lensMacro
@lens

Construct a lens from a field access.

Example

julia> using Setfield

julia> struct T;a;b;end

julia> t = T("A1", T(T("A3", "B3"), "B2"))
T("A1", T(T("A3", "B3"), "B2"))

julia> l = @lens _.b.a.b
(@lens _.b.a.b)

julia> get(t, l)
"B3"

julia> set(t, l, 100)
T("A1", T(T("A3", 100), "B2"))

julia> t = ("one", "two")
("one", "two")

julia> set(t, (@lens _[1]), "1")
("1", "two")

julia> # Indices are always evaluated in external scope; for properties, you can use interpolation:
       n, i = :a, 10
       @lens(_.$n[i, i+1])
(@lens _.a[10, 11])
source
Setfield.@set!Macro
@set! assignment

Shortcut for obj = @set obj....

Example

julia> using Setfield

julia> t = (a=1,)
(a = 1,)

julia> @set! t.a=2
(a = 2,)

julia> t
(a = 2,)
source
Setfield.@setMacro
@set assignment

Return a modified copy of deeply nested objects.

Example

julia> using Setfield

julia> struct T;a;b end

julia> t = T(1,2)
T(1, 2)

julia> @set t.a = 5
T(5, 2)

julia> t
T(1, 2)

julia> t = @set t.a = T(2,2)
T(T(2, 2), 2)

julia> @set t.a.b = 3
T(T(2, 3), 2)
source