0

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.

IBOED2
  • 151
  • 1
  • 2
  • 8
  • In the question marked duplicate the answers use procedures that aren't in r5rs which I specified I was using for my solution – IBOED2 Dec 03 '14 at 01:41
  • My own [solution](http://stackoverflow.com/a/27209078/201359) to that question is r5rs compatible, as long as you replace `begin0` with `let`. Take the time to read it and read the comments. – Óscar López Dec 03 '14 at 01:53
  • @IBOED2 My solution to that uses `let-values`, which is simply syntactic sugar around `call-with-values`. – Joshua Taylor Dec 03 '14 at 01:59

0 Answers0