How to keep track of current position in a list while doing deep recursion

34 views Asked by At

what I'm trying to do is take a symbolic expression, and replace all of its 'leaves' with the numbers in a list from left to right, so the left-most leaf should be replaced with 1, the next 2, etc, etc.

This is the code I have currently (I'm using R5RS, and I'm trying not to use mutation)

(define subst
  (lambda (sexp num)
    (cond ((null? sexp) '())
          ((not (pair? sexp)) (car num))
          (else (cons (subst (car sexp) num)
                      (subst (cdr sexp) (cdr num)))))))

(define numbers (list 1 2 3 4 5 6 7 8 9 10))

The output for:

(subst '(((a (d . e)) (b . c)) . (c . d)) numbers)

is:

'(((1 (2 . 3)) (2 . 3)) 2 . 3)

What I would like to be output is:

'(((1 (2 . 3)) (4 . 5)) 6 . 7)

I was thinking that I need to change num to cdr num in the previous recursion of subst when I come across and replace a leaf, but I don't see how I can do that without using set!

Any help would be appreciated, thanks.

0

There are 0 answers