tags:

views:

65

answers:

2

Does REMOVE ever return the same sequence in any real implementations of Common Lisp? The spec suggests that it is allowed:

The result of remove may share with sequence; the result may be identical to the input sequence if no elements need to be removed.

SBCL does not seem to do this, for example, but I only did a crude (and possibly insufficient) test, and I'm wondering what other implementations do.

CL-USER> (defparameter *str* "bbb")
*STR*
CL-USER> *str*
"bbb"
CL-USER> (defparameter *str2* (remove #\a *str*))
*STR2*
CL-USER> (eq *str* *str2*)
NIL
CL-USER> *str* 
"bbb"
CL-USER> *str2*
"bbb"
A: 

I suspect it mostly depends on the implementation. On the whole, I suspect it's not that common, as the typical case would be that something gets removed when REMOVE is called, so making a space optimisation for the nothing-removed case would incur a run-time penalty and not necessarily saving any space, since you'd want to allocate space for the return value for strings and arrays and would either need to construct a list as you go OR do a two-pass operation.

Vatine
+4  A: 

Returning the original string could be useful. In case no element of a string gets removed, returning the original sequence prevents allocation of a new sequence. Even if a new sequence has been allocated internally, this new sequence could be turned into garbage as soon as possible.

CLISP for example returns the original string.

[1]> (let ((a "abc")) (eq a (remove #\d a)))

T
Rainer Joswig