Can we override "="?

Topic says it all. If so how?
Thanks

1 Like

No.

2 Likes

I think the closest options are:

  • Override a[]=4 with setindex!.
  • Use a macro to make @changeequals a=4 do whatever you want.
1 Like

Actually I don’t think that the title does say it all: What do you actually want to do and why? It’s likely that there is a different / better solution.

6 Likes

On the other hand, the OP may want enlightenment rather than practical advice. @kristoffer.carlsson’s “No” follows from the fact that assignment is not a Julia function. In this respect, Julia differs from other (more-or-less) functional languages, and one assumes there is a good reason for this design. I have looked around for an explanation, without success. Perhaps @jeff.bezanson (or any other ur-developer) would be kind enough to restate the reasoning here.

5 Likes

This is pretty standard among scripting languages where = is always change of binding. Such semantics cannot possibly be implemented as a function and assignment is also used often enough that it will severely affect the predictability/inferability of the code if it’s behavior can be changed.

3 Likes

Seems totally possible to have an assign function which takes the new name wrapped in Val?

No. A function cannot do assignment.

I mean possible in the sense that it wouldn’t interfere with the compiler because the exact name of every assignment would be known to it.

It will interfere a lot since you still have to dispatch on the type (of RHS). Plus it’s basically never what assignment overload is overloaded on for the LHS.

While not exactly the same as overriding =, you could of course write a macro to parse the forms passed and do a transformation on any Expr with :(=) as its head.

2 Likes

First, you have to distinguish mutating assignment from simply binding names to values. Mutating assignment (e.g. to arrays, and possibly in the future to structs, a.b = c) can indeed be overloaded.

But binding is much more primitive. If binding were done by a function, how would the bindings for the arguments to that function be established? Clearly there would need to be some simpler, more primitive form of binding for that. So we choose to simplify the language by only exposing that more primitive form.

I think this makes programs easier to reason about, for the human and the computer. In a = f(x), you can know that a will refer exactly to the value of f(x). This is a powerful abstraction: you can name and juggle values around however you want, and nobody can tell! There is an airtight separation between how values are computed, and how consumers of those values refer to them.

11 Likes