The following is a slight modification of the implementation in Graham's book
"On Lisp." Question: How can one define a special form all-values such
that:
(all-values (find-sum n))
will return all the possible answers, i.e., all positive integer pairs that
make up n.
----------------- Scheme implementation ----------------
(define *continuation-stack* ())
(define fail ())
(call/cc (lambda (cc)
(set! fail
(lambda ()
(if (null? *continuation-stack*)
(cc 'done)
((pop *continuation-stack*)))))))
(defmacro choose choices
(if (null? choices)
'(fail)
`(call/cc
(lambda(cc)
(push *continuation-stack*
(lambda () (cc (choose ,@(cdr choices)))))
,(car choices)))))
(define (a-number lo hi)
(if (= lo hi)
lo
(choose lo
(a-number (1+ lo) hi))))
(define (2-numbers lo hi)
(list (a-number lo hi) (a-number lo hi)))
(define (find-sum n)
(let ((numbers (2-numbers 1 n)))
(if (= (apply + numbers) n)
`(the sum of ,@numbers is ,n)
(fail))))
--------------------------session-------------------
SCM Turtlegraphics Copyright (C) 1992 ···@cc.tut.fi, ···@cc.tut.fi
Type `(help-gr)' or `(help-turtlegr)' for a quick reference of
the new primitives.
> (find-sum 6)
(the sum of 1 5 is 6)
> (fail)
(the sum of 2 4 is 6)
> (fail)
(the sum of 3 3 is 6)
> (fail)
(the sum of 4 2 is 6)
> (fail)
(the sum of 5 1 is 6)