0

I'm doing a project for college in Common Lisp

And I need to compare a 4x4 list Example:

(
((white full circle) (black empty circle) (black full circle) (white empty circle))
(0 0 0 0)
(0 0 0 0)
(0 0 0 0)
)

I need to compare if a line have 4 lists that share an element, in this case "circle" and I can't use any defvar like intersection, need to use it recursively, and I can't find a way to do it

1 Answer 1

1

Try this:

(defun find-common (x)
  (labels ((compare (items lst)
            (cond ((null items) nil)
              ((not (remove-if #'(lambda (k) (member (car items) k)) lst))
               (cons (car items) (compare (cdr items) lst)))
              (t (compare (cdr items) lst)))))
    (cond ((null x) nil)
      (t (cons (compare (caar x) (car x)) 
               (find-common (cdr x)))))))

To see if a list of list shares a common element, we have to check if each element in the car of that list also occurs in each list of its cdr. That's what the compare function does. It checks if an element occurs in all the lists recursively.

The find-common function recursively searches for all common occurrences in the list of lists.

Let's assume table is your 4 x 4 list:

(setf table
    '(((white full circle) (black empty circle) (black full circle) (white empty circle))
      ((3 2 8 5) (2 9 1 8) (23 8 2 1) (3 8 0 2))
      ((one five six) (six one five) (five one six) (one six five))
      ((green blue red) (green red blue) (silver red white) (green yellow blue))))

Calling the find-common function:

>(find-common table)

((CIRCLE) (2 8) (ONE FIVE SIX) NIL)
2
  • Don't use defun in a function body. It does not do what you think it does. It will define a top level function. Use flet or labels to define local functions. Also, please use proper indentation and code formatting.
    – Svante
    Dec 13, 2014 at 13:44
  • @Svante, Thanks. Edited the answer accordingly.
    – Kidus
    Dec 13, 2014 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.