Reputation: 9
I wanted to know how I can remove nil elements from an array in lisp. Here is my code so far:
(dotimes (i arr)
(when (null (aref arr i)
(remove null (aref arr i))))
(return arr))
However, this code does not seem to work
Upvotes: 0
Views: 242
Reputation: 38789
(dotimes (i arr)
(when (null (aref arr i)
(remove null (aref arr i))))
(return arr))
Your code calls dotimes
which is a loop over integers, but with arr
in argument which is an array. There's no automatic conversion from arrays to integers, if you wanted to iterate over the indices of the vector you would call (length arr)
to get the size of the vector.
Inside the loop, you search the first occurrence of a nil element then return out of the loop. There's no need to do that.
Since vector are contiguous sequences of values, removing and element is something that must be taken care of for the whole array, as it leaves holes that requires moving elements somehow (either by modifying the sequence or by computing a new array).
That's why there's no setf
version of element deletion for vectors.
Calling (remove null (aref arr i))
assumed that the element at position i is a sequence itself, from which you compute a new sequence where null
(not nil
) is removed, but due to the surrounding when
this sequence is the empty list nil
. Also, the result of remove
is not used.
It looks like you are trying to apply rules from another language, maybe Javascript, to Common Lisp but you really need to refer to the actual documentation or reference manuals for the language you are using.
Also when learning try to do small code examples and fix them first before trying to do bigger tasks otherwise there are too many bugs to fix at once.
Upvotes: 0
Reputation: 780724
If you want to modify the array in place, use DELETE
(delete nil arr)
If you want to create a new array, use REMOVE
once, not in a loop.
(setq new-arr (remove nil arr))
Upvotes: 4