help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Need help in understanding an example of recursion


From: Nikos Apostolakis
Subject: Need help in understanding an example of recursion
Date: Sat, 02 Jun 2007 12:09:19 -0400
User-agent: Gnus/5.11 (Gnus v5.11) Emacs/23.0.51 (gnu/linux)

Hello group,

I was browsing the source code of SAGE, and I tried to implement in
elisp the function that computes all the partitions of an integer n.
So I did the following:

(defun nea-partitions (n)
  "Return a list with all partitions of the integer n."
  (if (= n 0)
      '(nil)
    (nea-next-partitions (nea-partitions (- n 1)))))

(defun nea-next-partitions (lst)
  (append (mapcar (lambda (x) (cons 1 x)) lst) 
          (dolist (elt (reverse lst) value)
            (when (and elt 
                       (or (= (length elt) 1) 
                           (> (car elt) (cadr elt))))
              (setq value (cons (cons (1+ (car elt)) (cdr elt)) 
                                value))))))

But this doesn't work:

(nea-partitions 0) 
  => (nil)
(nea-partitions 1) 
  => ((1))
(nea-partitions 2) 
  => ((1 1) (2))
(nea-partitions 3) 
  => (1 1 1) (1 2) (3) (2))
(nea-next-partitions '((1 1) (2))) 
 => ((1 1 1) (1 2) (3))
(nea-next-partitions (nea-partitions 2))
  => ((1 1 1) (1 2) (3) (2))

Is there some subtle[0] point about recursion that I am missing?
Any help in understanding this will be greatly appreciated.

TIA,
Nikos 


[0] for my level of understanding at least.





reply via email to

[Prev in Thread] Current Thread [Next in Thread]