[plt-scheme] On continuations...

From: michael rice (nowgate at yahoo.com)
Date: Fri Dec 17 15:21:46 EST 2004

In trying to firm up my rather dim understanding of
continuations I've translated a Python function for
generating the partitions of an integer into a Scheme
function.

It seems to work properly for several examples but I
don't have a feeling whether it's a decent translation
or a terrible hack.

Example at bottom of file. Comments appreciated!

  --mr  



;def partitions(n):
;	# base case of recursion: zero is the sum of the
;empty list
;	if n == 0:
;		yield []
;		return
;		
;	# modify partitions of n-1 to form partitions of n
;	for p in partitions(n-1):
;		yield [1] + p
;		if p and (len(p) < 2 or p[1] > p[0]):
;			yield [p[0] + 1] + p[1:]



(define (part-gen n eot)
  (letrec ((return #f)
	   (cont (lambda (x)
		   (set! cont (lambda (x) (partition n)))
		   (cont #f)))
	   (partition (lambda (n)
                        (if (zero? n)
                            (call/cc (lambda (c) (set!
cont (lambda (x) (return eot))) (return '())))
                            (let ((pg (part-gen (- n
1) eot)))
                              (do ((p (pg) (pg)))
                                ((equal? p 0) eot)
                                (call/cc (lambda (c)
(set! cont c) (return (append '(1) p))))
                                (when (and (not (null?
p))
                                           (or (<
(length p) 2)
                                               (>
(second p) (first p))))
                                  (call/cc (lambda (c)
                                             (set!
cont c)
                                             (return
(append (list (+ (car p) 1)) (cdr p))))))))))))  
    (lambda () (call-with-current-continuation
		(lambda (ret) (set! return ret) (cont #f))))))



;Welcome to DrScheme, version 206p1.
;Language: Swindle.
;> (let ((pg (part-gen 6 0)))
;    (do ((p (pg) (pg)))
;      ((equal? p 0))
;      (display p)
;      (newline)))
;(1 1 1 1 1 1)
;(1 1 1 1 2)
;(1 1 2 2)
;(2 2 2)
;(1 1 1 3)
;(1 2 3)
;(3 3)
;(1 1 4)
;(2 4)
;(1 5)
;(6)
;> 



		
__________________________________ 
Do you Yahoo!? 
Yahoo! Mail - Find what you need with new enhanced search.
http://info.mail.yahoo.com/mail_250



Posted on the users mailing list.