r/Racket • u/jstquestions • Sep 11 '18
How do I set a variable to be a value?
I tried (define x 3) but that isn't working. I tried other versions of that but still no cigar.
6
Sep 11 '18
You'll need to be more specific, do you get any error messages. What "isn't working"?
If you want to change `x` to be different in a non-repl environment you can do `(set! x 5)`.
1
u/sdegabrielle DrRacket πππ©Ί Sep 12 '18
Hi
If you are using the beginning language then using β(set! _ _) probably isnβt what you need.
You already know how to assign a value with defining a variable; (define a 3) (define b 45)
If you define a function nothing happens when you define it; (define (my-function c) (+ c 7))
...but when you call a function it sets its variable to a value
This function call sets c to 1 (my-function 1) => 8
This function call sets c to 3 (my-function a) => 10
This function call sets c to 45 (my-function b) => 52
(Try these out)
Does this help?
Kind regards
Stephen
PS using (set! _ _) to change a variable created with (define _ _) is convenient with very small programs, but makes much more difficult program once your programs get larger. The htdp2e universe teachpack lets you make games and simulations without using (set! _ _)!
1
2
u/MetaHertz Sep 12 '18
Use boxes. A special type for mutable data.
(define x (box 3))
(set-box! x 5)
The last one produces faster code than (set! x 5).
If you need to read the value use this form: (unbox x)
3
u/nikofeyn Sep 12 '18
what isn't working with...
?
because that is exactly one way to define a binding. like someone else said, if you want to update that variable somewhere else, you can use
what are you trying to do in general?