X++ operator

Are there plans to implement an operator like x++? Can it be created by the user? Thanks.

The ++ operator exists as a user extensible operator, but it is infix rather than postfix. That is, x++ is not a valid expression but x ++ y is.

5 Likes

Assuming you’re talking about the increment operator like in C, you can mimic the pre-increment ++i with a macro:

julia> macro ++(x::Symbol)
           return :( $(esc(x)) = $(esc(x)) + 1 )
       end
@++ (macro with 1 method)

julia> i = 2
2

julia> @++ i
3

julia> i
3
3 Likes

You can write x += 1 to increment x.

17 Likes

make it a package! PlusPlus.jl?

1 Like

Name taken, twice

2 Likes

But this one would be better, so… PlusPlusPlus.jl?

4 Likes

and they do the *same thing (almost) the same way…

1 Like

I’ll take a look at PlusPlus.jl. I really like the syntax of C and also Julia. I thought a native x++ would be nice. I actually use x += 1.

Thanks.

To be fair, x++ would probably not promote the type the way that x += 1 does. Perhaps instead x += true, though I don’t claim to like using boolean literals for the purpose of preventing promotion.

julia> Meta.@lower  x += 1
:($(Expr(:thunk, CodeInfo(
    @ none within `top-level scope'
1 ─ %1 = x + 1
│        x = %1
└──      return %1
))))
julia> typeof(Int8(3) + 1)
Int64

julia> typeof(Int8(3) + true)
Int8
3 Likes

I am not sure that C’s ++ increment would be a good fit for Julia. First, recall that x can be any generic value (eg a Date), so the generic solution is most likely

x += oneunit(x)

which is shorthand for x = x + oneunit(x).

While ++ could expand to this, the hidden/implicit = it would introduce its own host of complications (eg surprises in scoping).

Also, ++ used extensively for loops & similar in C/C++. Julia has higher level constructs, you so situations where you have to manually increment counters are more rare.

2 Likes

This is a good observation: while there are some constructs like += that expand to assignment, at least they all involve the = somewhere in the syntax, which serves as a hint that an assignment is occurring. In C, assignment is not so significant since you have to explicitly declare every variable (I was habitually about write C/C++, but assignment is very significant, subtle and complex in C++, so I’m intentionally leaving it out). C also has a model where variables do actually behave semantically like memory locations (you can take an address of any variable), whereas in Julia a variable is just a name associated with a value.

6 Likes