0

I'm pretty new to Scheme and I'm currently working in DR Racket to learn it. So basically my problem is that I'm having trouble permanently changing global variable.

This is my change function:

(define (change b) (set! b (- b 1)) b) 

As you can note I return the value of a at the end of the function. And this is the output on the console.

> (define a 4) > (change a) 3 > a 4 

As you can see, in the function it returned the value of 3 (4 - 1). But it seems as though the global variable didn't actually change when i call it after the function. How do I leave it changed? Thanks in advance.

4
  • I know Clojure, not Racket, but it looks like you create a global symbol a, then name the parameter of change the same thing, and change the local a. Commented Mar 10, 2017 at 0:03
  • 1
    Also, this doesn't look like a very functional way of going about things. Mutating globals should be avoided like the plague. Commented Mar 10, 2017 at 0:05
  • No, I tried changing the variable names to defer but that didn't work Commented Mar 10, 2017 at 0:14
  • In C, if you make one variable int a = 5 , then pass a to a fucntion where the variable is bound to b and in it do b = b+1, why wouldn't the global variable a change? The same answer is valid for Scheme as well. Commented Mar 10, 2017 at 1:04

2 Answers 2

5

First, Racket is NOT Scheme. They both are similar in this example, but they are very different languages. And calling them the same thing is similar to saying C and C++ are the same language.

Now, on to your actual reference.

The reason change doesn't appear to do anything is because you are passing the 'value' into b, rather than any actual variable.

If you want to pass the actual reference of a primitive like this what you need to do is to box it with the box function. Then you can use set-box! to do the actual mutation, and unbox to get the value in the box

Giving you the following function:

(define (change b) (set-box! b (- (unbox b) 1)) b) 

Now when you use the change function, the variable should update.

> (define a (box 4)) > (change a) '#&3 > a '#&3 > (unbox a) 3 

(The '#& is just a compact way that the Racket repl says that the next value is in a box. Which is why we get 3 when you unbox it.)

There are plenty of other data structures to that will have the same effect, vectors, structs, etc. But for a single value box is the simplest.

Sign up to request clarification or add additional context in comments.

Comments

3

You're not truly changing the global variable! you're just modifying a parameter, which for all practical purposes is acting as a local variable. If you want to modify the global one, don't pass it as a parameter:

(define a 4) (define (change) (set! a (- a 1)) a) a => 4 (change) => 3 a => 3 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.