Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: my first Lisp code...comments welcome

27 views
Skip to first unread message

WJ

unread,
Feb 28, 2015, 1:51:48 AM2/28/15
to
> (defun compositions (n k)
> "Return a list containing all K-element lists of non-negative
> integers with sum N. Caller guarantees that N,K are non-negative
> integers."
> (if (zerop k)
> (if (zerop n) (list nil) nil)
> (loop for first-item upfrom 0 to n nconc
> (mapcar (lambda (tail) (cons first-item tail))
> (compositions (- n first-item) (1- k))))))


Gauche Scheme:

(use srfi-42)

(define (compositions n k)
(if (zero? k)
(if (zero? n) (list '()) '())
(append-ec (: first-item (+ 1 n))
(map (cut cons first-item <>)
(compositions (- n first-item) (- k 1))))))

gosh> (compositions 4 3)
((0 0 4) (0 1 3) (0 2 2) (0 3 1) (0 4 0) (1 0 3) (1 1 2) (1 2 1) (1 3 0)
(2 0 2) (2 1 1) (2 2 0) (3 0 1) (3 1 0) (4 0 0))
0 new messages