I'm playing around with implementing looping using call/cc and wrote a map function like this:
(define (map1 f l)
((lambda (state)
(let ((cc (car state))
(l (cadr state))
(m (caddr state)))
(if (null? l) (reverse m)
(cc (list cc (cdr l) (cons (f (car l)) m))))))
(call-with-current-continuation
(lambda (kk) (kk (list kk l '()))))))
So far so good, (map1 (lambda (n) (+ n 2)) '(3 5 11 17)) returns (5 7 13 19).
Next I wanted to get rid of the list encapsulation in the state argument with multiple values in the following function:
(define (map2 f l)
(call-with-values
(lambda () (call-with-current-continuation
(lambda (kk) (kk (values kk l '())))))
(lambda (cc l m)
(if (null? l) (reverse m)
(cc (values cc (cdr l) (cons (f (car l)) m)))))))
Racket, Chez, Chicken, gauche and scm all give errors that 1 value was expected but 3 received. Interestingly, gambit gives the expected result (the one I expected, that is). What am I missing in my understanding of call-with-values and/or call/cc? Or can someone re-write my map2 so it works?
(kk kk l '()); novaluesvaluesin the initial "generator", but not the call to the continuation itself. (yeah the documentation is Racket's, but it works in Racket's r5rs mode, I checked).values. So in the generator both(values kk l '())and(kk kk l '())will work, while in the receiver only calling the continuation will work.