Search code examples
lispcommon-lisp

How to intercalate 2 lists in lisp and print a statement when the list lengths don't match


How do you intercalate two lists and check for matching list lengths and print a statement when the lengths don't match? I can make it continue when one list becomes null, but how to error it out completely from the start when lengths don't match?

(defun intercalate (list1 list2)
  (cond 
    ((and (eql list1 nil) (eql list2 nil)) nil)
    ((null list1) list2)
    (t (cons (first list1) (intercalate list2 (rest list1))))))
(print (intercalate '(1 3 5) '(2))) 

will return

(1 2 3 5)

but i want it to return

"List lengths must match"


Solution

  • Here is a simple solution:

    (defun intercalate (list1 list2)
      (labels ((recursive (list1 list2)
                 (cond ((null list1)
                        (when list2 
                          (return-from intercalate "List lengths must match")))
                       (t (cons (first list1) (recursive list2 (rest list1)))))))
        (recursive list1 list2)))
    

    For instance:

    CL-USER> (intercalate '(1 3 4) '(10 20 30))
    (1 10 3 20 4 30)
    CL-USER> (intercalate '(1 3 4) '(2))
    "List lengths must match"