CSC 160 Computer Programming for Non-Majors Chapter 4: Conditional Expressions and Functions Prof. Adam M. Wittenstein
Dealing with Conditions To deal with conditions, we need to have a way of saying a condition is true or false. We need a new class of values, which are called booleans or truth values.
Section 4.1: Booleans and Relations
Another type of data: Boolean (= (+ 3 4) 7) returns true (> (+ 3 4) 7) returns false = : number number -> boolean > : number number -> boolean Same for =, <=
Built-in operations on Booleans (and true false) returns false (or true false) returns true (not true) returns false not : boolean -> boolean and, or: boolean boolean … -> boolean
Example 1: True or false On paper, decide what results you would expect from the following Scheme conditions: On paper, decide what results you would expect from the following Scheme conditions: 1) (and (> 3 4) (>= )) 2) (or (> 3 4) (= )) 3) (not (= 4 (+ 1 3)))
Is the parameter of the right type? To determine if an object (number, boolean, symbol, string, image, etc.) is of a given type, DrScheme has predefined functions: boolean? : object -> boolean (tells whether the object is a boolean) number? : object -> boolean (tells whether the object is a boolean) There are similar functions called string?, symbol?, and image?. eq? : object object -> boolean (tells whether two objects are the same)
Section 4.2: Functions that Test Conditions
Our first Boolean-valued function ; under-21? : number -> boolean “Examples of under-21?:” (under-21? 17) “should be” true (under-21? 48) “should be” false (under-21? 21) “should be” false ; Idiom: functions returning boolean end with ?
Our first Boolean-valued function ; under-21? number -> boolean (define (under-21? age) … age … ) “Examples of under-21?:” (under-21? 17) “should be” true (under-21? 48) “should be” false (under-21? 21) “should be” false
Our first Boolean-valued function ; under-21? number -> boolean (define (under-21? age) (< age 21) ) “Examples of under-21?:” (under-21? 17) “should be” true (under-21? 48) “should be” false (under-21? 21) “should be” false
In Summary… Booleans are another atomic (simple) data type. They are used to test if something is true or false. By convention, a Scheme function that returns a boolean has a ? at the end of its name. Other than that, booleans work the same way as all the other data types we have worked with this semester. Next time… Writing more boolean-valued functions Discuss HW7 Review for Quiz