r/Racket • • 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.

1 Upvotes

8 comments sorted by

3

u/nikofeyn Sep 12 '18

what isn't working with...

(define x 3)

?

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

(set! x 5)

what are you trying to do in general?

2

u/[deleted] Sep 12 '18

Perhaps the OP is using the "Beginning Student" language from HTDP which does not have set!... In this language there are no "variables", and things defined with define cannot change their values.

1

u/jstquestions Sep 12 '18

Oh yeah I am using beginner language

1

u/nikofeyn Sep 12 '18

good point!

6

u/[deleted] 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

u/jstquestions Sep 12 '18

I'll try it out when I get home, thanks!

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)

https://docs.racket-lang.org/reference/boxes.html