xxxInPlace or xxxCopy?
Andrej Mitrovic
andrej.mitrovich at gmail.com
Wed Jan 19 20:23:29 PST 2011
On 1/20/11, Andrej Mitrovic <andrej.mitrovich at gmail.com> wrote:
> One common mistake newbies make in Python is calling the sorted method
> and expecting it to sort in place:
>
>>>> x = [3, 2, 1]
>>>> sorted(x)
> [1, 2, 3] < sorted returned a new list
>>>> x
> [3, 2, 1] < x stayed the same
>>>>
>
> There are a few functions in the Python lib that have "InPlace" added
> to their names to avoid confusion, so it's not a new convention and it
> seems like a good way to go.
>
What I meant by the first sentence is that due to the interpreter
outputing the sorted list, a newbie might think that x was sorted, so
he uses it in his own code until he notices the bug.
I think what might help out in D is if we had a way to mark some
functions so the compiler guarantees that their return values *are
not* to be discarded. For example, this code will compile:
import std.stdio;
import std.string;
void main()
{
string s = "Mary has a lil lamb.";
replace(s, "lil", "li'l"); // returns a copy, but discards it
}
If the replace function is marked with some kind of @nodiscard
annotation, then his would be a compile error since it doesn't make
sense to construct a new string, return it, and discard it.
But maybe that's going overboard. How often do these kinds of bugs creep in?
More information about the Digitalmars-d
mailing list