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)
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