Skip to content

Multi argument modify? #137

Description

@jw3126

From time to time, I do an add hoc implementation of the following functionality:

using Setfield
import Setfield: modify

"""
    modify(f, obj, obj1, obj2..., lens)

Multi argument `modify`. Apply `set` to `obj` with the value obtained from `f` on the `get` of all objects.

"""
function modify(f, objects_lens...)
    lens = last(objects_lens)
    args = let objects = Base.front(objects_lens),
        lens=lens
        map(objects) do o
            get(o, lens)
        end
    end
    val = f(args...)
    o1 = first(objects_lens)
    return set(o1, lens, val)
end

Usage is as follows:

meas1 = (unit=:cm, values=[1,2])
meas2 = (unit=:cm, values=[3,4])
modify(+, meas1, meas2, @lens(_.values))
(unit = :cm, values = [4, 6])

It has footgun potential though:

meas1 = (unit=:cm, values=[1,2])
meas2 = (unit=:mm, values=[3,4])
modify(+, meas1, meas2, @lens(_.values))
(unit = :cm, values = [4, 6])

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions