Scheme pass-by-reference

前端 未结 7 1457
忘了有多久
忘了有多久 2021-02-08 11:09

How can I pass a variable by reference in scheme?

An example of the functionality I want:

(define foo
  (lambda (&x)
    (set! x 5)))

(define y 2)

         


        
7条回答
  •  醉梦人生
    2021-02-08 11:55

    You can affect an outer context from within a function defined in that outer context, which gives you the affect of pass by reference variables, i.e. functions with side effects.

    (define (outer-function)
      (define referenced-var 0)
      (define (fun-affects-outer-context) (set! referenced-var 12) (void))
      ;...
      (fun-affects-outer-context)
      (display referenced-var)
    )
    (outer-function) ; displays 12
    

    This solution limits the scope of the side effects.

    Otherwise there is (define x (box 5)), (unbox x), etc. as mentioned in a subcomment by Eli, which is the same as the cons solution suggested by erjiang.

提交回复
热议问题