Is there a Julia function similar to the R function `with`?

For fun.

julia> macro with(container, expressions...)
           esc(:( let (; $(propertynames(getfield(__module__, container))...))=$container
               $(expressions...)
           end ))
       end
@with (macro with 1 method)

julia> let t=(a=2, b=3)
           @with t a+b
       end
5

julia> tup = NamedTuple(Symbol(c)=>c for c ∈ 'a':'j')
(a = 'a', b = 'b', c = 'c', d = 'd', e = 'e', f = 'f', g = 'g', h = 'h', i = 'i', j = 'j')

julia> @with tup (j, i, h, g, f, e, d, c, b, a)
('j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a')

julia> tup = (a=1, b=2, c=3)
(a = 1, b = 2, c = 3)

julia> @with tup begin
           local temp=a+b
           temp+c
       end
6

You can compare this against this macro. But you should also consider whether such a thing is even worthwhile, considering this.

Edit:

Oops, I polluted my global namespace. The above code does not, infact, work for locally-declared named tuples; it only works for globally-visible objects.

Looks like this works though. It’s quite clever.

3 Likes