Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme pass-by-reference

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)

(foo y)

(display y) ;outputs: 5

Also, is there a way to return by reference?

like image 816
Cam Avatar asked Jul 16 '10 05:07

Cam


People also ask

How are arguments passed in schemes?

Scheme allows you to express this by writing a mostly normal-looking parenthesized sequence of argument names, followed by a dot and the name of the argument to receive the list of the remaining arguments. (If no extra arguments are passed, this argument variable will receive the empty list.)

What is pass-by-reference in C?

Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. In C, the corresponding parameter in the called function must be declared as a pointer type.

What is pass by value and pass-by-reference in C++?

The difference between pass-by-reference and pass-by-value is that modifications made to arguments passed in by reference in the called function have effect in the calling function, whereas modifications made to arguments passed in by value in the called function can not affect the calling function.

How do you pass a variable by reference in C++?

Pass by reference is something that C++ developers use to allow a function to modify a variable without having to create a copy of it. To pass a variable by reference, we have to declare function parameters as references and not normal variables.


2 Answers

See http://community.schemewiki.org/?scheme-faq-language question "Is there a way to emulate call-by-reference?".

In general I think that fights against scheme's functional nature so probably there is a better way to structure the program to make it more scheme-like.

like image 176
Jari Avatar answered Sep 19 '22 01:09

Jari


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

like image 25
erjiang Avatar answered Sep 21 '22 01:09

erjiang