2015-10-06

posted Oct 6, 2015, 5:00 AM by Samuel Konstantinovich   [ updated Oct 6, 2015, 8:05 AM ]
Goal: The wrath of COND!!!! conditional statements vs if statements

Open your lab from yesterday. We will go over it and discuss how to solve it. (see solutions at bottom of this post)

New statement, the conditional

;Using many if statements connected together
;starts to make the code go across the screen:

(define g 79)
(if (> g 99)
    "OK"
    (if (> g 90)
        "Whats wrong n00b?"
        (if (> g 80)
            "At least I will feed you..."
            "No soup for you!")))

;Scheme has a better way to do this!

(cond
   ( <clause> )
   ( <clause> )
   ( <clause> )
...
   ( <clause> )
)


each clause is
 boolean_expression    any_expression

You look at the clauses from top to bottom, and when a boolean is true, you use the value of the any_expression on that line.
(cond
   (  ( > x 10)  2 )
   (  ( > x 20)  3 )
   (  ( < x 0)  4 )
)

when x is 11 you get 2
when x is 19 you get 2
when x is 21 you get 2 because the 1st line is true, and it doen't get past it.
when x is -11 you get 4
when x is 5 you get NOTHING!!!! this is really bad

(cond
   (  ( > x 20)  3 ) ; now we fixed the 3 never showing up
   (  ( > x 10)  2 )
   (  ( < x 0)  4 )
   (  #true  5 )  ; now we fixed the no-result from happening
   ;because #true will always happen no matter what
)

when x is 11 you get 2
when x is 19 you get 2
when x is 21 you get 3
when x is -11 you get 4
when x is 5 you get 5

Example of cond in a function:

(define condDemo (lambda (x)
                   (cond
                     ((< x 10) 2 )
                     ((< x 7)  3 )
                     ((> x 20) 4 )
                     (else 99 ) ;else is the same result
                     ;as using #true
                     )))
(condDemo 15)


Try grade conversion with cond:

(gradeConvert g) -> one of the results below, assume g is an integer from 0 to 100 inclusive.

90-100:  "Q"
80-89 :  "M"
70-79 :  "X"
<70   :  "Z"



SOLUTIONS TO OLD LABS:
(define isBetween (lambda (a b n)
                    (or
                     (and (> n a) (< n b))
                     (and (< n a) (> n b)))))
;alternate
;                     (and (> n (min a b)) (< n (max a b)))))

;alternate 2
;         (or 
;                     (< a n b)
;                     (> a n b))))



(define xor (lambda (a b)
              (and (or a b)(not (and a b)))))
;              (not (equal? a b))))
(xor #true #true)
(xor #true #false)
(xor #false #true)
(xor #false #false)
Comments