I’m trying to compare two booleans :
(if (equal? #f (string->number "123b"))
"not a number"
"indeed a number")
When I run this in the command line of DrRacket I get "not a number" , however , when I
put that piece of code in my larger code , the function doesn’t return that string ("not a number") , here’s the code :
(define (testing x y z)
(define badInput "ERROR")
(if (equal? #f (string->number "123b"))
"not a number"
"indeed a number")
(display x))
And from command line : (testing "123" 1 2)
displays : 123
Why ?
Furthermore , how can I return a value , whenever I choose ?
Thanks
Try this:
You were discarding the result of the
ifexpression. The condition was working fine, but nothing was done with the resulting string, it just went ignored. The whole procedure now is returning#<void>, becausedisplayis a side-effecting operation with no value of its own. Also, I removed thebadInputvariable and theyandzparameters because they were not being used at all.To return a value from a procedure, simply put the expression with the value you want to return at the end of the procedure’s body – this explains why your code wasn’t working, only the last expression returns a value, although you can do side-effecting operations (for example, calling
display) with any expression before and including the last one.As a matter of fact, your code can be written in a more idiomatic by returning a value, noticing that the condition in the
ifnow actually depends on thexparameter being passed:EDIT:
Regarding the last edit to your question, I believe you’re looking for something like this:
Or this, if you prefer to use a
cond: