Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme - dynamic scope and infinte loop

Tags:

scope

lisp

scheme

I read a book about scheme, and it has the next example:

(define map
   (lambda (f s)
     (if (null? s)
         '()
          (cons (f (car s))
                (map f (cdr s)))))

(map (lambda (s)
        (set! s '(1 2 3 4))
        'hello)
     '(a b c d))

It say that in dynamic scope, we will enter to infinite loop. But why? As I understood, After we apply the application, we arrive to map with

f = (lambda (s)
        (set! s '(1 2 3 4))
        'hello)

and s= '(a b c d). Now, for the first run, we will apply f on (car '(a b c d):

((lambda (s)
    (set! s '(1 2 3 4))
    'hello)
 (car '(a b c d)))

And now, It change a to be (1 2 3 4). And so on.. Where is the loop here?

like image 698
Adam Sh Avatar asked Mar 15 '26 01:03

Adam Sh


1 Answers

I think what the author means is that after f (car s) executes, the value of s will be '(1 2 3 4), so the value of (cdr s) will be '(2 3 4), so you'll call (map f '(2 3 4)) every time ad infinitum.

However I do not think this is an accurate depiction of dynamic scoping. Since s is a parameter to the lambda (and thus not a free variable), only that parameter should be affected by the set! and the s of the map function should be unaffected. So there should be no infinite loop - whether you're using dynamic scoping or not. And if I translate the code to elisp (which is dynamically scoped), the code does in fact not cause an infinite loop. So I'd say your book is wrong in saying there'd be an infinite loop using dynamic scoping.

like image 101
sepp2k Avatar answered Mar 18 '26 08:03

sepp2k