I am learning about racket/scheme and came across an online resource that said, if a function written using a cond gives true or false, it can be rewritten using only not, and, and or. I have worked out some simple examples where I was able to to convert cond statements into a statement only involving not and and or. My question is if there is a way that the logic can be "seen" right away when converting between these two types of statements. I understand that it is not always practical to convert every cond statement into a combination of not's and's and or's but I am interested in learning about the logic behind the process of converting. Thanks in advance.
(If something about the question does not make sense, leave a comment and I will try clarifying what I want to understand)
All conditional expressions (and not only those evaluating to true/false) can be rewritten using only boolean combinators. This is because of how logical operators are evaluated in Scheme/Racket. For instance, logically
(and a b)
would be true if botha
andb
are true, and otherwise false. But in Racket, the result of(and a b)
isb
if botha
andb
are truthy, and otherwise false. That is, evaluation proceeds to the right until either the last argument or a falsy value is encountered. At that point, evaluation stops and that value (which could be a boolean but needn't be) is returned. It's becauseand
andor
don't simply produce boolean output that they can be used to stand in for conditional expressions.E.g.
But you wouldn't usually want to use them that way since they're hard to read. As a general guideline, use
if
andcond
in most cases, rather than elementary boolean operators. If you only care about taking action on a positive or negative result of the conditional, then you could usewhen
orunless
. If you do care about handling both positive and negative results, but one of them is a boolean result such as this example:... then this would be a case where a boolean operator would be preferable, like so:
If both arms of the
if
conditional are boolean values, like this:... then just replace the entire conditional expression with the condition itself:
Otherwise, stick to
if
andcond
.