2017-09-19 HW06

posted Sep 19, 2017, 6:22 AM by Samuel Konstantinovich   [ updated Sep 19, 2017, 6:56 AM ]
Goal: Decision making in scheme (conditionals)

Do Now:
On paper: Write the scheme functions:

(myMaxOf3 a b c) -> do not use the built in max function.

(isMultipleOf x y) that returns true when x is a multiple of y, false otherwise.


MyMax Solutions:
(define (myMax a b)
  (+
   (/ (abs (- a b)) 2)
   (/ (+ a b) 2)))

(define (midpoint a b)
  (/ (+ a b) 2))

(define (dist a b)
  (abs (- a b)))

(define (myMaxAlt a b)
  (+
   (midpoint a b)
   (/ (dist a b) 2)))




Classwork:

If statements:
(if <boolean expression>
  <expression1>
  <expression2>)

When the boolean expression is true, the entire if evaluates to expression1.
When it is false, the entire if evaluates to expression2.
Example1:
(if (> 10 2)
    (+ 1 2)
    (- 2 3))

a) First evaluate the boolean 
(if (> 10 2)
    (+ 1 2)
    (- 2 3))
b) choose which statement to pick
(if #T
    (+ 1 2)
    (- 2 3))
c) Replace the entire if with just that statement
(+ 1 2)
d) evaluate that statement
3

Example2:
(if (= (remainder x 2) 0)
    (> x 0)
    (< x 0))

;assume x is 5:
a) First evaluate the boolean   (= (remainder 5 2) 0) -> (= 1 0) -> #F
(if (= (remainder x 2) 0)
    (> x 0)
    (< x 0))


b) choose which statement to pick
(if #F
    (> x 0)
    (< x 0))
c) Replace the entire if with just that statement
(< x 0)  which is (< 5 0)
d) evaluate that statement
#F



If statements can go inside functions as well:

(define (foo x)
      (if (> x 3)
          1
          2))
(foo 1) is 2
(foo 2) is 2 
(foo 3) is 2
(foo 4) is 1
(foo 5) is 1

(define (bar x y)
      (if (and (> x 0) (> y 0))
          10
          20))

(bar 1 2) is 10
(bar -1 2) is 20
(bar -3 -4) is 20
(bar 4 -9) is 20
(bar 12 5) is 10

YOUR TURN TO WRITE CODE!

Go To SchemingBat
http://bert.stuy.edu/pbrooks/SchemingBat/scheming.py

Lab + HW6
Choose: Simple decisions and do the 1st 5 problems (up to three-part function) 
a. Write and save your work in DrRacket, because the website does not save it for you!
b. BEFORE you submit to the website, come up with 4 test cases.
c. Test your work in drRacket, then paste into the website to verify that you are correct.
d. Submit all 5 problems in the HW06 slot as a comment.
Comments