category
category

Reputation: 2155

stack overflow when executing recursive lisp function

I get a '-Program stack overflow' prompt in clisp when I try to execute the following recursive function that, I believe, returns the most common element in a list:

(defun greater-member (lst)
  (cond  ((null (cdr lst))
                (cons (car lst) (count-if #'(lambda (x) (eql x (car lst))) lst)))
         ((>= (count-if #'(lambda (x) (eql x (car lst))) lst)
              (count-if #'(lambda (x) (eql x (car (remove (car lst) lst)))) lst))
                (greater-member (remove (car (remove (car lst) lst)) lst)))
         (t (greater-member (remove (car lst) lst)))))

e.g greater-number should return as follows:

>(greater-number '(a a a b b b b c))
(b . 4)  

May I ask, what is causing the overflow? I've gotten rid of all the little syntax errors by repeatedly executing greater-number in clisp- the function seems to hold logically.

Upvotes: 1

Views: 459

Answers (2)

category
category

Reputation: 2155

I've realized my error now.

Looking at my null test, rather than

(null (cdr lst)) 

I should have

(null (remove (car lst) lst))

So that the redundant, lesser occurring unique elements are removed.

Upvotes: 6

user797257
user797257

Reputation:

A little bit more optimized version:

(defun most-common (list)
  (let* ((len 0) (hash (make-hash-table))
         (max-occurences 0)
         key
         (max-possible
          (dolist (i list (ceiling len 2))
            (incf (gethash i hash 0))
            (incf len))))
    (maphash #'(lambda (a b)
                 (if (>= b max-possible)
                     (return-from most-common
                       (if (> b max-occurences) a key))
                     (progn
                       (when (> b max-occurences)
                         (setf key a max-occurences b))
                       (decf max-possible (max 1 (floor b 2))))))
             hash) key))

Upvotes: 1

Related Questions