I have an assignment for my CS functional languages class where we must write a function able to detect whether or not a given list is circular at its beginning. The function has to be recursive. Let's name it circular
:
* (setf list1 '(a b c d))
* (rplacd (cddr list1) list1)
* list1
#1=(A B C . #1#)
* (circular list1)
t
* (circular '(a b c a b c))
nil
Now, I know how to check for circularity in this case : at some point along the recursion, an atom a cons
in the list is going to share the same address as the list itself, hence the circularity. Here is my function so far :
(defun circular (list &aux list2)
(setf list2 list)
(cond
((null list) nil)
((eq (car list) list2) t)
(t (circular (cdr list))) ) )
I thought that by comparing the car
of list
against list2
at every point of the recursion the function would eventually return a result, but while the function does work for non-circular lists, it becomes infinitely recursive when I try to use it on a circular list. I am sure that I am missing something incredibly obvious here, but still, any help would be immensely appreciated!
&aux
parameter directly:&aux (list2 list)
. – Nonproductivecons
is not anatom
. – Radmen