I'm currently studying Scheme for a course at my university, while looking at some exercises I got stuck on this particular one. Professor has yet to answer my previous mails therefore I have more chances to receive an answer here faster.
Given this code
(define (list-iter-cc lst)
(call/cc
(lambda (return)
(for-each
(lambda (x)
(call/cc (lambda (next-step)
(return (cons x next-step)))))
lst)
'end)))
I have to use it to write the iter
macro whose syntax is
(iter <a variable symbol> in <a list> <code>)
example:
(iter x in '(1 2 3)
(display x)
(newline))
Since I couldn't understand list-iter-cc
i went to see the solution, which i don't understand as well. The solution:
(define-syntax iter2
(syntax-rules (-> in)
((_ var in lst code ...)
(let loop ((head (list-iter-cc lst)))
(unless (eq? head 'end)
(let ((var (car head)))
code ...
(loop ((cdr head)))))))))
To unravel the macro I tried writing the following
> (define head (list-iter-cc '(1 2 3 4)))
> head
'(1 . #<continuation>)
> (let ( (var (car head))) (display var))
1
> (define head2 (cdr head))
> (let ( (var2 (car head2)) ) (display var2))
Xxx X car: contract violation
expected: pair?
given: #<continuation>
>
which is exactly what I thought would happen.
list-iter-cc
's return continuation is called at the first iteration of the for-each inside the first lambda, returning with cons x next-step
.
x
is the first element of the list and next-step
is a continuation.
1). what is the content of next-step
? the following iteration of the for-each
? how can it evaluate to 'end
after the last iteration?
2). assuming that in the macro head (list-iter-cc lst)
is '(1 . #<continuation>)
, the car is 1
and it gets displayed, but after looping over its cdr, var (car head)
will be the car of the continuation! how can it possibly evaluate to 2
and then 3
and then 'end
, and why this does not happen in the code I tried writing to understand it?
Any help would be appreciated, especially one that could guide me step by step.