I tried solving this problem Flip-coin takes no arguements and returns the symbol heads or tails at random with equal probability. This is what I got, but I do not understand why it is giving me the "impossible" can this be stopped?
(define flip-coin
(lambda ( )
(cond
[ (= (random 2 ) 1 ) "heads" ]
[ (= (random 2 ) 0 ) "tails" ]
[else "impossible" ]
)
)
)
You have two different calls to random
in your cond
statement. Both of these are independent and can give you different results. So it's possible that the first (random 2)
evaluates to 0
and the second one evaluates to 1
, making both of those cases fail and giving you "impossible"
.
The solution would be to put the result of (random 2)
in a local variable with a let-statement, making sure to only call random
once.
The flip-coin
procedure returns only one of two possible values, it can be simplified a bit more, also noticing that random
should be called only once - and there's no need to save its value in a variable, because the result is used immediately:
(define (flip-coin)
(if (zero? (random 2))
"tails"
"heads"))
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