Underscores.jl icon indicating copy to clipboard operation
Underscores.jl copied to clipboard

Assignment gets read as a keyword

Open mcabbott opened this issue 5 years ago • 3 comments

Something which ought to work, I think:

mutable struct Bar x end; bars = [Bar(i) for i in 1:3];

@_ map(_.x, bars) # fine

@_ foreach(_.x = 2, bars) # ERROR: syntax: invalid keyword argument name "(_1,) -> begin

Originally from broadcasting setproperty!, here: https://github.com/JuliaLang/julia/issues/36608

mcabbott avatar Jul 10 '20 17:07 mcabbott

Hm yes I think this should probably be made to work. I'm a little leery about possible visual ambiguities with keyword syntax — are there any super confusing combinations?

I'm thinking about things like f(_.x=1, y=_+1)... it's unambiguous but pretty confusing!

c42f avatar Jul 13 '20 04:07 c42f

I hadn't realised that keywords worked at all, but they do, and may even be useful:

@_ sort(bars, by=-_.x)

Perhaps @_ f(_=_+1) should remain an error, but apart from that, testing the keyword's args[1] isa Symbol seems like it ought to be safe.

mcabbott avatar Jul 13 '20 06:07 mcabbott

Yes, keywords work intentionally

https://github.com/c42f/Underscores.jl/blob/fc332c499a8bb1d9d3f54ad81205c7bde1d0563c/src/Underscores.jl#L27

Perhaps @_ f(_=_+1) should remain an error, but apart from that, testing the keyword's args[1] isa Symbol seems like it ought to be safe.

I think the rule might be that if args[1] is a symbol which is not _, then it's a keyword. Otherwise it might be a function (or a syntax error) and we could try replace_(Expr(:(=), args...)). Then if that results in a closure use that instead of an Expr(:kw) ?

c42f avatar Jul 14 '20 05:07 c42f