Why can't subseq cope with a dotted list?
1st July 2019
Although subseq is usually used with strings, in Common Lisp it is also quite useful with lists; for example:
> (subseq '(a b c d e) 1 3) (B C)
However, I found a curious thing about the LispWorks implementation of subseq; it doesn't like improper lists, even if it should be possible to give the correct answer; for example:
> (subseq '(a b c d . e) 1 3) Error: In a call to LENGTH of (A B C D . E), tail E is not a LIST.
Why is it worrying about the dotted pair at the end of the list if it can perfectly well get elements 1 to 3?
In other situations a dotted pair at the end of a list doesn't cause any problems; for example:
> (mapcar #'cons '(x y z) '(a b c d . e)) ((X . A) (Y . B) (Z . C))
Just to confirm that I haven't overlooked something I tried writing my own recursive version of subseq:
(defun mysubseq (list from to) (cond ((> from 0) (mysubseq (cdr list) (1- from) (1- to))) ((= from to) nil) (t (cons (car list) (mysubseq (cdr list) from (1- to))))))
Let's try this with a dotted list:
> (mysubseq '(a b c d . e) 1 3) (B C)
So it seems fine, and I can see no reason why the built-in version shouldn't be able to handle dotted lists too.
blog comments powered by Disqus