Scheme pass-by-reference

前端 未结 7 1448
忘了有多久
忘了有多久 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 12:06

    Like Jari said, usually you want to avoid passing by reference in Scheme as it suggests that you're abusing side effects.

    If you want to, though, you can enclose anything you want to pass by reference in a cons box.

    (cons 5 (void))
    

    will produce a box containing 5. If you pass this box to a procedure that changes the 5 to a 6, your original box will also contain a 6. Of course, you have to remember to cons and car when appropriate.

    Chez Scheme (and possibly other implementations) has a procedure called box (and its companions box? and unbox) specifically for this boxing/unboxing nonsense: http://www.scheme.com/csug8/objects.html#./objects:s43

提交回复
热议问题