Grundrage
Grundrage

Reputation: 13

Memory allocation and the call stack in scheme

When Scheme code is run by the computer, how does it set up and use the stack frame? Moreover, how does Scheme do its memory management?

For instance, if I were to run the following code in scheme

(define add_func x
    (lambda (y) (+ x y))

(map (add_func 2) (cdr (list 1 2 3)))

Then where is the function returned by add_func stored in memory. Is add_func stored on the stack? Also, is (list 1 2 3) stored in the same stack frame as (cdr (list 1 2 3))? Does every () denote a new stack frame?

Upvotes: 1

Views: 467

Answers (1)

C. K. Young
C. K. Young

Reputation: 223033

Scheme does not specify specific memory management strategies or layouts. In particular, it is possible to implement Scheme to allocate all call frames on the heap and not use a call stack. In fact, using the heap for call frames makes it easier to implement continuations.

Your add_func (which I'll hereafter refer to as add-func in line with the conventional Scheme naming style) is not defined correctly. I presumed that you meant this instead:

(define (add-func x)
  (lambda (y) (+ x y)))

Although Scheme does not specify how things are stored in memory, the procedure returned by add-func is most likely stored in the heap, and not associated with any particular call frame.

Upvotes: 3

Related Questions