r/ProgrammingLanguages • u/bakery2k • Jan 07 '26
Discussion Distinguishing between mutating and non-mutating methods
A List class might have methods such as l.insert(obj), which obviously mutates the list in-place, and l.take(5), which obviously returns a new list. However other methods like sort could reasonably work either way.
Assuming a language designer wants to offer both kinds of sort method, how could they be named so that programmers don't get them confused? I am aware of a few precedents:
Swift calls the in-place method
sortand the non-mutating methodsorted- but breaks that convention for well-known operations from functional programming likemap(which is non-mutating)- Python uses the same naming convention as Swift, but moves non-mutating versions to stand-alone functions, only using methods for in-place versions
- Ruby calls its two methods
sortandsort!, where the latter is in-place. However!has a more general meaning - it's widely used for "more dangerous" versions of methods
Another option would be to only provide non-mutating methods and require the programmer to manually write l.sort!() as l = l.sort(). However, in that case it's far from obvious that l.sort() on its own is effectively a no-op (it creates a sorted list and then throws it away).
Do other languages use other naming conventions to distinguish between mutating and non-mutating methods? Or is there a different approach you'd recommend?
32
u/Bob_Dieter Jan 07 '26
Julia uses the same
sort/sort!convention, but the ! symbol at the end of functions always means mutating one of the arguments, so there is no confusion.22
u/Han_Sandwich_1907 Jan 07 '26
The exclamation mark is common to Lisp dialects to indicate effectful/impure functions
14
u/yuri-kilochek Jan 07 '26
Why is it obvious? It could return a new list instead.
16
u/kohugaly Jan 07 '26
C++ and Rust mark methods as mutating or non-mutating by specific syntax (a
const/mutkeyword). This actually has semantic meaning and is then actually enforced by the compiler, both in the function body and at the call site.In C++ the syntax for this is to append
constkeyword at the end of the declaration like this:In Rust, methods have explicit
selfargument, which explicitly specifies in what way is the self argument being accessed: taken by value, by immutable reference, by mutable reference, unique smart pointer, or shared smart pointer. The mutable reference version looks thusly:Naming conventions are not a reliable way to do this. In fact they are not reliable way to do anything. Human languages are not consistent and explicit enough. You either make the convention into explicit syntax rule with semantic meaning, or you will have to be dealing with ambiguity.
7
u/Daniikk1012 Jan 07 '26
The ! seems nice, it's what Scheme does as well. However, there it's just part of the function name, not enforced. Maybe introduce function coloring? If you use mutating operations on arguments of a function, that function must be marked as mutating (It's not necessary to mark it as such if mutating operations are only used on variables introduced in the function body itself)
6
u/Isogash Jan 07 '26
Personally I quite like the ! syntax, would be interesting to have a language which actually enforced it for mutating/non-mutating methods.
5
u/ScottBurson Jan 08 '26
I agree that careful choice of names for functional (non-mutating) operations is important. I recall reading once that new users of Java's
BigIntegerclass are often confused by the fact that a method namedadd, for instance, is functional. I contend that the method should have been namedplusinstead. Someone writingx.add(y)might reasonably expectxto be modified, butx.plus(y)doesn't have the same connotation; it sounds likex + y.So I think names of functional operations shouldn't be verbs, or at least not verbs that suggest modification (e.g.,
findseems okay). I tried to adhere to this principle when designing FSet, my functional collections library for Common Lisp. So for instance, adding an element to a set iswith, and removing one isless.Alas, I haven't stuck to this perfectly; FSet does have seq operations
insertandsort, for instance. Maybe I should rename them.4
u/tikhonjelvis Jan 07 '26
Seems like you'd want a naming convention one way or another, since an in-place function and a copying function could—and probably should—have different implementations with different observable characteristics (ie performance).
If your language has static types, you can get away with the convention being a bit less obvious (or even less consistent) because the types make it clear. The version that returns a copy would return a value, while the version that sorts in place would return
()(orIO ()or whatever). You could couple this with a warning about usingl.sort()and throwing the value away. I've used several languages with warnings like this; they can be a bit annoying at times but, probably, worth it overall. (If the programmer really intended to throw the value away, the solution would be writing something like_ = l.sort().)If you don't have types, you'll need to have a stronger and more "obvious" convention. For that, I second the suggestion of using
sort!like Julia does; I've seen that myself in Lisp variants, and it was both intuitive and clear at a glance.4
u/LegendaryMauricius Jan 07 '26
I have one argument be marked 'var', which really just means the function also returns the same field/member (with a possibly different value). So it's like a functional language, except with the whole returning a different value thing being implicit.
Mutating happens by marking the mutated variable with '!'. That way you don't need to use assignment to store the new value. So 'push(numbers!, 3)' is the same as 'numbers = push(numbers, 3)'.
Of course the function call ABI is optimized for the first version, but this allows the programmer to reuse functions for both mutating and calculation, so you don't need to implement both 'operator+' and 'operator+=' like in C++ for example.
4
u/rjmarten Jan 08 '26
In Mismo, functions can be overloaded by parameter passing convention where
mutmeans "pass by mutable reference" andletmeans "pass by immutable reference". SoYou can leave off the let/mut if only one overload matches, otherwise the compiler will prompt you to specify.
(Haven't yet figured out a good syntax for making this work with UFCS, ie
arr.sort())3
u/ultrasquid9 Jan 07 '26
For modern languages, i think the language itself should distinguish between the two, which the LSP can then report on. Something like this, as a potential example:
3
u/Ronin-s_Spirit Jan 08 '26
JS has the same inconcistency problem where
map()makes a new array, but in general it tries to saysort()andtoSorted().2
u/mesonofgib Jan 07 '26
I quite like the
!syntax, but the problem is that no (few?) languages actually enforce it.Since I work entirely in languages that don't support
!in a name, I've found other ways to get around this; I've settled on a convention where if the method name is a verb, such assort(), then it's mutating. Non-mutating functions get something more likeorderedBywhere I'm trying to convey through the method name that this method returns something new.The other thing that helps is if the compiler warns you (or even errors) if you call a function that returns a value but you don't observe it.
2
u/jcklpe Jan 07 '26
Personally I prefer making all the functions non mutating. In my language mutation is always explicit. So any function performed on a thing is a no op unless you explictly bid the value to the variable name.
2
u/tobega Jan 08 '26
I would go for immutability being the default and enforcing a "mut" keyword on every parameter that gets mutated. You can just mark an object method as mut if it mutates its object.
The virality creates a simple checkable "type system".
When I've floated this previously, the C++ crowd brings up how bad "const" is. Yes, const is really bad! But I don't think "mut" will be, because it is a much more meaningful marker.
2
u/tmzem Jan 08 '26
As you mentioned, the ! sigil is often used as a mutation indicator. However, you can make this approach more consistent by using a ! sigil (or another symbol of your choice) to mark a mutation in both the caller and in the parameter list. If your language is OOP, this also requires the "this"/"self" parameter to be explicitly stated in the parameter list, similar to Rust of Python:
Then, calling the function uses the ! as postfix operator to explicitly pass as mutable at the call site:
Since you only mark parameters, this system can work for all parameters, not just the "object" itself.
You can also extend the system and put mutability on the type, rather then the parameter for even stronger guarantees, but if the added complexity is worth the trouble is a whole different question.
3
u/Hixie Jan 08 '26
I think this is probably the right answer. IMHO it can be justified as not breaking the convention because by convention "map" is an operation that returns an iterable, so if you "map" a list you're not going to mutate the list. I agree that it's a little iffy though.
2
u/Jhuyt Jan 07 '26
If using an lsp or ide you can add often quivkly check the signature which should include if the function is mutating or not (if the language has syntax for it). That's my preferred approach.
1
u/brucejbell sard Jan 07 '26 edited Jan 07 '26
I would prefer different names, based on the focus of the language. Even if there are other cues available (like method vs. standalone function), I like different names as redundant, self-explanatory cues.
So, for a functional-first language,
sortwould be the "normal", non-mutating version, whilesort_inplacecould be a mutating version, or you could borrow Lisp's naming convention forsort!.On the other hand, for an imperative-first language,
sortwould be the "normal", mutating version, and you could stealsortedfrom Python/Swift.Other options can also use distinct names, like
sort_stablefor a guaranteed stable sorting function.1
u/Guvante Jan 07 '26
C++ has [[nodiscard]] to avoid confusion on whether sort sorts in place or returns a new value by making it a compiler warning to ignore the new list that is returned if it is a new value.
Doesn't solve the general problem of course (for instance if you return a value that makes sense in either case).
1
u/--predecrement Jan 07 '26 edited Jan 07 '26
Raku has an execution model that enables semantic variants that most other PLs don't have, and a similar story applies to its parsing model and syntax variants.
Of relevance to your question are its distinctions between "mutation" of a "variable" (with two sub-variants, namely mutation via assignment and via binding, which have distinct Wikipedia pages because they really are very distinct programming level semantics!), and "mutation" of a "value", and mapping of the above semantics to appropriate syntax, with even standard Raku supporting the following combination:
----
This is reminiscent of the
!suffix notation used by some PLs, but it's definitely different.On the plus side, one doesn't write two variants of the method, just one (preferably one that does not mutate it's invocant directly but instead just returns the mutated version of its invocant), and
.=can be used for any such method.On the minus side, it's not in-place mutation, and that can be too slow for large data sets unless suitable data structures are used.
I can imagine there being two versions of a method, a non-mutating one that gets dispatched to for "ordinary"
.barinvocations and another in-place mutating one that gets dispatched to for.=bar invocations. (But I'm not convinced that would be a good idea.)----
In practice, standard Raku has a mix of solutions that are what Rakoons have decided were the most ergonomic on a method-by-method basis, suggesting that perhaps the kind of eclectic mixtures one sees in Ruby et al (and standard Raku) naturally arise when ideology and dogma are held at bay.
In addition, going beyond standard Raku, it lets users, individually, or in small groups / teams / sub-communities, create whatever combinations of its semantics and syntax they like, and have their code interoperate with those who choose differently (bolstered by such morphing of languages being lexically scoped).
(And while it might sound like you end up with chaos and the lisp curse, in reality the opposite has happened.)
1
u/WittyStick Jan 07 '26 edited Jan 08 '26
One approach is to simply use the same names and signatures via an interface, but use fluent interfaces for the mutable versions.
A trivial example:
We can use
l = l.append(x)for either version. If we ignore the result ofl.append(x)for the mutable version it doesn't matter - it is still mutated. Thel = l.append(x)is a mutation and then effectively a no-op assignment, because it's assigning the resulting value back to the same variable.1
u/mister_drgn Jan 07 '26
Aside from using different names, Swift requires the "mutating" keyword for methods that mutate structs. It doesn't require this for methods that mutate classes because it's kinda trying to be two different languages at the same type, one OOP and one closer to functional.
In general, you might look to functional languages for inspiration. Some, like Haskell, only allow pure functions which have no side effects. Recently, a few functional languages have begun exploring algebraic effect systems, which require you to specify in a function's signature whether it produces any side effects (and which side effects it produces). See experimental languages like Unison and Koka for this.
1
u/TallAverage4 Jan 08 '26
Two things that I think are generally helpful here is warnings due to implicitly discarding (that way
l.sorted()will give a warning about the discard) and distinguishing between mutable and immutable pointers/references1
u/TheAncientGeek Jan 09 '26
You can use different operators to both clarify and endure mutation versus non mutation , eg. list<-sort() versus list->sort().