I'm working in Racket but as far as I know this is the case in Scheme in general; you cannot do something like this because we are trying to define something in an expression context:
(if condition
(define x "do a backflip")
(define x "do a barrel roll"))
Now for this particular case I could do something like this instead:
(define x
(if condition
"do a backflip"
"do a barrel roll"))
But if you have a lot of different things to define this gets really awful, because instead of
(if condition
(begin (define x "do a backflip")
(define y "awesome")
(define z "shoot me"))
(begin (define x "do a barrel roll")
(define y "nice")
(define z "give me sweet release")))
we get
(define x
(if condition
"do a backflip"
"do a barrel roll"))
(define y
(if condition
"awesome"
"nice"))
(define z
(if condition
"shoot me"
"give me sweet release"))
Which isn't as DRY as it could be, we are constantly repeating the test for condition
. And the result is that if instead of testing for condition
we want to check for other-condition
, we have to make changes n
times for n
the amount of things being defined. Is there a better way to do this, and if so: How?
Use define-values
:
(define-values (x y z) (if condition
(values "do a backflip" "awesome" "shoot me")
(values "do a barrel roll" "nice" "give me sweet release")))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With