The less-familiar parts of Lisp for beginners — ldiff and tailp

Next, the ldiff and tailp functions.  These are fairly simple in their descriptions, but it is important to note that they look for sublists that are eq, not equal.  That is, their special behaviour is only apparent on sublists that are part of the list they’re being compared against.  An example might help:
 

CL-USER> (let ((list-1 '(1 2 3 4 5 6))
               (list-2 '(4 5 6)))
           (format t "ldiff on non-eq lists: ~A~%"
                   (ldiff list-1 list-2)))
ldiff on non-eq lists: (1 2 3 4 5 6)
NIL
CL-USER> (let* ((list-1 '(1 2 3 4 5 6))
                (list-2 (cdddr list-1)))
           (format t "ldiff on true sublists: ~A~%"
                   (ldiff list-1 list-2)))
ldiff on true sublists: (1 2 3)
NIL
CL-USER> (let ((list-1 '(1 2 3 4 5 6))
               (list-2 '(4 5 6)))
           (format t "tailp on non-eq lists: ~A~%"
                   (tailp list-2 list-1)))
tailp on non-eq lists: NIL
NIL
CL-USER> (let* ((list-1 '(1 2 3 4 5 6))
                (list-2 (cdddr list-1)))
           (format t "tailp on true sublists: ~A~%"
                   (tailp list-2 list-1)))
tailp on true sublists: T
NIL

So, as long as you remember this constraint, and also remember that the order of the arguments is reversed between tailp and ldiff, you will have no troubles with these functions.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.