Lisp, of course :-) Common Lisp's SETF and related macros work this way. E.g.,
(incf (ldb (byte 3 5) x))
would increment the "byte" (CL's term for an arbitrary bit field) of width 3 at offset 5 of X.INCF is defined in terms of SETF. Of course, the set of macros that can update a place is user-extensible. So if you wanted one that multiplies the value in the place by two, you could just write something like this (the trailing "f" in the name, as you might guess, is the convention for such a macro):
(define-modify-macro doublef () (lambda (x) (* x 2)))
then you could call it like this: (doublef (ldb (byte 3 5) x))
to double the value in the bit field.(EDIT: used lambda expression instead of helper function.)
I have some old code somewhere for images which I'm sure does something to the effect of:
image[x, y] *= scale;
where Image::operator[] returns a Pixel&.Consider the much-hated vector<bool>, implemented as a packed bit array. Since you can't return a reference to a bit, operator[] must create a special wrapper class that holds a reference to the word and the bit offset, and then overload operator= and perform other tricks. It's famously leaky and gross.
In Swift, we can implement this optimization much more cleanly. inout lifetimes are always scoped, and when the scope ends, the new value is written back to the object via its setter. Our `inout boolean` is not backed by a boolean at all: it's backed by a getter and setter which can do arbitrary things, like mask and shift a word.
You might object that special forms are still privileged, e.g. foo[idx]+=1. But in fact these are not special: one of the surprising features of Swift is that inouts work on computed properties. For example, say we add a mutable property highHalf on UInt64:
Now you can do this: So complex references can be used for any inout. That's how array indexing works.Swift is the first language I've encountered that works this way; are there others?