The video lecture 3a states you can write map using an iterative process. I don't see how that is possible though. It seems like cons can only add something to the front of a list.
MIT 6.001 Structure and Interpretation of Computer Programs, Spring 2005
Stacey Warren - Expert brainly.com
Hey! We 've verified this expert answer for you, click below to unlock the details :)
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.
Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
I got my questions answered at brainly.com in under 10 minutes. Go to brainly.com now for free help!
The usual recursive map would be something like this:
(define (map fn lst)
(if (empty? lst)
(cons (fn (car lst))
(map fn (cdr lst)))))
To make map an iterative process, you could use append to add elements to the back:
(define (map fn lst)
(define (map-iter inlist outlist) ; internal procedure to transform
(if (empty? inlist) ; inlist to outlist
(map-iter (cdr inlist) ; tail-recursive (iterative) call to map-iter
(append outlist ; with rest of the inlist and appended outlist
(list (fn (car inlist)))))))
(map-iter lst '())) ; just calls map-iter with empty outlist
Append joins two lists, so (list elem) is needed here.
(map sqrt '(1 4 9 16)) ; --> '(1 2 3 4)
Nice! That makes map itself iterative, but I think that just pushes the problem into append. Wouldn't append have to be recursive (and not iterative) to accomplish this?
I just looked up the source to append in mit scheme.
The comments above say that it uses a finite amount of stack space. The code is a bit complex. It seems to me like it is able to do this by mutating the list. There is a reference to set-cdr! in the code.