0
votes

I am quite confused with cond statements -

I am wondering how I would write something along the lines of this using just the one cond:

(define (name x)
  (cond [(statement 1 is true)
           [(if statement 1 and statement 2 are both true) *print*]
           [(if statement 1 is true and statement 2 is not) *print*]])

  [else (statement 1 is false)
           [(if statement 1 is false and statement 2 is true) *print*]
           [(if statement 1 and statement 2 are both false) *print*]])

(pseudo conditions)

Thank you

2
simple boolean algebra... and, or, not. Then write a truth table. You only have 2 inputs so you can only have 4 possible outcomes. Edit: A truth table might result in 4 cond clauses (incl the else), but will still be cleaner than the nested if.leppie
Alternatively, you dont have to check for "statement 1" in the nested if as they have been already evaluated.leppie
It is the syntax itself I am confused about @leppieFΣynman

2 Answers

1
votes

Since you are mentioning statement-1 and statement-2 I think your code can be heavily optimized since nested if has already determined the state of statement-1. here is how I see it:

(if statement-1
    (if statement-2 ; statement-1 consequent
        consequent-1-2-true
        alternative-1-true-2-false)
    (if statement-2 ; statement-1-alternative
        consequent-1-false-2-true
        alternative-1-2-false))

statement-2 will only be evaluated once since statement-1 will either be false or true.

A cond is more useful when you have a simple if-elseif where only the alternative has nested ifs.

(cond (predicate-1 consequent-1)
      (predicate-2 consequent-2)
      ...
      (predicate-n consequent-2)
      (else alternative))

Now you could use a let to calculate the statements in advanced and use and to check that more than one are true:

(let ((result-1 statement-1) (result-2 statement-2))
  (cond ((and result-1 result-2) consequent-1-2-true)
        (result-1 consequent-1-true-2-false) 
        (result-2 consequent-1-false-2-true)
        (else alternative-1-2-false))) 

Of course this let is not necessary if the statements are variables themselves and thus cached. Notice that the tests after the first don't need to check that one is true and the second is not since we know that both cannot be true, then the previous consequent would have fired and the cond had been done. All the perdicates can assume all previous predicates were false.

When writing code it's better to think about what makes the code easier to read and understand. In this case I would not have used cond since the nature of your problem has even nesting on both the consequent and alternative.

0
votes

Just a followup to my second suggestion (not an answer):

(define (name x)
  (if 'statement 1 is true'
      (if 'statement 2 is true'
          *print1*
          *print2*)
      (if 'statement 2 is true'
          *print3*
          *print4*)))

This covers the boolean cases.