Marco Baringer <mb@bese.it> wrote:
+
 >> look into a technique called "trampolining". basically you'd rewrite

 my bad. this technique is used when CPS transforming code, since my
 example wasn't written in a CPS style ... it failed to prove my point.

 here's an example which actually works. it's a recursive function for
 calculating the length of a list. just so it's clear what i'm doing
 i've started with the "normal" recursive version and rewritten it
 until it's in trampolined CPS form..
+
But note that even in trampolined CPS form it is not necessary to use
THROW (which, when deeply nested, might be quite slow) to achieve the
desired result. Consider this slight rewrite [which, with no THROW,
allows replacing #'TOPLEVELK with #'IDENTITY]:
> (defun lentramp (list k)
(if (null list)
(lambda () (funcall k 0))
(lambda ()
(lentramp (cdr list) (lambda (v) (funcall k (1+ v)))))))
LENTRAMP
> (trace lentramp)
NIL
> (defun runtramp (func)
(loop for f = func then (funcall f)
while (functionp f)
finally (return f)))
RUNTRAMP
> (runtramp (lambda () (lentramp '(a b c d e) #'identity)))
0: (LENTRAMP (A B C D E) #<Function IDENTITY {1019F481}>)
0: LENTRAMP returned #<Closure Over Function "LAMBDA (LIST K)" {48519951}>
0: (LENTRAMP (B C D E) #<Closure Over Function "LAMBDA (LIST K)" {4851A2F9}>)
0: LENTRAMP returned #<Closure Over Function "LAMBDA (LIST K)" {4851B9D1}>
0: (LENTRAMP (C D E) #<Closure Over Function "LAMBDA (LIST K)" {4851C379}>)
0: LENTRAMP returned #<Closure Over Function "LAMBDA (LIST K)" {4851DA19}>
0: (LENTRAMP (D E) #<Closure Over Function "LAMBDA (LIST K)" {4851E3C1}>)
0: LENTRAMP returned #<Closure Over Function "LAMBDA (LIST K)" {4851FA29}>
0: (LENTRAMP (E) #<Closure Over Function "LAMBDA (LIST K)" {485203D1}>)
0: LENTRAMP returned #<Closure Over Function "LAMBDA (LIST K)" {485219E9}>
0: (LENTRAMP NIL #<Closure Over Function "LAMBDA (LIST K)" {48522391}>)
0: LENTRAMP returned #<Closure Over Function "LAMBDA (LIST K)" {48523921}>
5
>
Rob

Rob Warnock <rpw3@rpw3.org>
627 26th Avenue <URL:http://rpw3.org/>
San Mateo, CA 94403 (650)5722607