Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Racket: Change two constants with one function

I wanna change two constants at the same time with one function, but somehow it doesn't work:

(define p 1)
(define q 1)

(define (change p q)
  (set! p (+ p 1))
  (set! q (+ q 1))) 
like image 747
JimBoy Avatar asked Feb 26 '26 13:02

JimBoy


1 Answers

It's probable that you're using a language that doesn't have implicit begin inside procedure bodies, so let's try writing it explicitly:

(define p 1) ; declare variables as global, so they 
(define q 1) ; can be modified inside a procedure

(define (change-vars) ; don't pass them, they won't get modified inside proc
  (begin ; use begin to evaluate expressions sequentially from left to right
    (set! p (+ p 1))
    (set! q (+ q 1)))) ; value of last expression is returned, here's #<void>

It works as expected:

p
=> 1
q
=> 1

(change-vars)

p
=> 2
q
=> 2
like image 192
Óscar López Avatar answered Mar 01 '26 10:03

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!