1 Replies - 1845 Views - Last Post: 21 April 2015 - 04:15 AM

#1 streek405  Icon User is offline

  • D.I.C Addict

Reputation: 15
  • View blog
  • Posts: 721
  • Joined: 10-March 13

Scheme: how to update a global variable in a function

Posted 20 April 2015 - 10:37 PM

I have tried using set!, define, and let() but none of them are updating my global variable. How the heck do you update a global variable???

UPDATE: never mind, set! does work I guess, I must be messing up elsewhere in my code because I just created this little test and set! works in here...

#lang racket

(define x 1)

(define getX
  (lambda(s)
    (updateX s)
    x)
  )

(define updateX
  (lambda (n)
    ;(define x n) fails
   ; (let() x n) ; fails
    (set! x n); works...
    x))

This post has been edited by streek405: 20 April 2015 - 10:46 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Scheme: how to update a global variable in a function

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2500
  • View blog
  • Posts: 3,955
  • Joined: 21-June 11

Re: Scheme: how to update a global variable in a function

Posted 21 April 2015 - 04:15 AM

As you found out, set! does work. define and let on the other hand define a new variable - they don't update existing once. In your real code you might have a situation where you have a global variable and a local variable of the same name and you then use set! on the local variable (the global variable won't be accessible while a local variable of the same name is in scope) and then, when the local variable goes out of scope, you read the global variable and notice that it has not changed.

PS: You might want to consider whether your approach is the best one for your problem. Mutable state is usually discouraged in Scheme and global mutable state is discouraged pretty much anywhere.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1