2 ms·
sort being likewise destructive in TXR Lisp is a bit of a regret of mine; we can easily have a nsort (non-consing sort) be destructive, and sort being equivalen
by kazinator 7y ago
sort being likewise destructive in TXR Lisp is a bit of a regret of mine; we can easily have a nsort (non-consing sort) be destructive, and sort being equivalent to (nsort (copy obj) ...).
I think that the designers get seduced by the fact that we have such good techniques for in-place sorting that the idea of sorting becomes synonymous with those techniques.
You would never implement a non-destructive sort first and then add an accompanying destructive one; the non-destructive one is the afterthought.
The Javascript blog doesn't really nail things here. It's perfectly legitimate to return "this" and mutate, and possibly useful. For instance, we could have an accumulator object such that:
accumulator(42).add(1).add(1).sub(4)
ends up with 40. Returning the object allows for threading through expressions like this, which works imperatively also.
In the case of Lisp, the destructive sort must return a value that is captured, because if the object is a list, and that list is sorted by a re-arrangement of the cons cells, the original list reference is quite likely longer a reference to the entire list.
Returning a value that the caller must capture also allows the operation to be specified as being destructive or not. If the caller never touches the input object after passing it into the operation, and just uses the returned one, it cannot tell.
Returning a value also allows for a succinct fix for broken code. If the sort was not intended to be destructive in some (f (sort x) y) expression, you just insert (f (sort (copy x)) y) instead of a verbose workaround like (let ((xc (copy x)) (f xc y)).
Likewise in the accumulator case, if we want to avoid mutating some original accumulator, we could have a copy method:
var new_acc = old_acc.copy().add(1).mul(2) // old_acc stays 42, new_acc is 86.