Search code examples
lispcommon-lisp

Writing a function to search for matches in lists


I'm trying to make a function that will return true if it finds a match for an item in another list. But it seems like everything should work, but on a call (f1 '(2) '(1 2 3)) return nil

(defun f1 (x y)
 (cond 
  ((null y) x)
  ((equalp x (car y))
  (t (f1 x (cdr y))))))

Solution

  • Your code after I auto-format it in Emacs is as follows:

    (defun f1 (x y)
      (cond
       ((equalp x(car y))
        (t(f1(x (cdr y)))))))
    

    There is one clause in the cond, so the part that starts with (t ...) is in fact a call to function t (which does not exist). Also, you are calling f1 with (x (cdr y)) but x is not a function either.

    You are also comparing x with (car y), but in your test you pass two lists as arguments:

    (f1 '(2) '(1 2 3))
    

    I think you should first write an auxiliary function belongs-to, which finds if some value exists in a list:

    (defun belongs-to (value list)
      "Returns non-NIL if VALUE is found in LIST using EQUALP"
      (cond
        ;; empty list
        (... NIL)
        ;; general case - match head of list
        (... T)
        ;; general case - recurse on tail of list
        (T (belongs-to ... ...))))
    

    Once you have this function, you can use it in f0:

    (defun f0 (x y)
      (and x (or (belongs-to ... ...)
                 (f0 ... y))))