Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

scheme - dynamic scope - why this is the return value?

why under dynamic scope this code will return error for "g not defined"? when running ((ff) 5), at some point g will get a value (the f lambda) and will be inserted into the runtime stack.

(
let ((f (lambda (g)
  (lambda (n)
   (if (zero? n)
    1
    (* n ((g g) (- n 1))))))))
((f f) 5)
)
question from:https://stackoverflow.com/questions/65945323/scheme-dynamic-scope-why-this-is-the-return-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With dynamic scope you don't have closures. Eg.

(define val #f)

(define (get-val val)
  (lambda ()
    val))

(define getter (get-val 5))
(getter) ; => #f

With lexical scope val from get-val lives in the returned procedure as a free variable and would return 5, but in dynamic scope it stopped existing right ather the proceudre was returned. The val referred in the procedure is whatever bound val in the dynamic scope. Eg.

(let ((val 10))
  (getter)) ; ==> 10

So val from the let became the closest binding with that name ad getter returned that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...