CS115 - Module 3 - Booleans, Conditionals, and Symbols

Similar documents
Module 3: New types of data

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used)

CS115 - Module 4 - Compound data: structures

Module 5: Lists. Readings: HtDP, Sections 9, 10.

Module 4: Compound data: structures

Module 4: Compound data: structures

Module 8: Local and functional abstraction

CS115 - Module 9 - filter, map, and friends

Module 10: Imperative Programming, Modularization, and The Future

Module 9: Trees. If you have not already, make sure you. Read How to Design Programs Sections 14, 15, CS 115 Module 9: Trees

CS115 - Module 10 - General Trees

Lists. Readings: HtDP, sections 9 and 10. Avoid 10.3 (uses draw.ss). CS 135 Winter : Lists 1

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2).

Working with recursion

Outline. Helper Functions and Reuse. Conditionals. Evaluation Rules for cond. Design Recipe with cond. Compound Data

Use recursion to write a function that duplicates the following function: (def (f L) (map (lambda (x) (+ (sqr x) x)) L))

The syntax and semantics of Beginning Student

The syntax and semantics of Beginning Student

The Design Recipe Fall 2017

Module 01: Introduction to Programming in Python

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction

CS115 - Module 1. Cameron Morland. Fall Cameron Morland CS115 - Module 1

ormap, andmap, and filter

Module 10: General trees

Local definitions and lexical scope

Local definitions and lexical scope. Local definitions. Motivating local definitions. s(s a)(s b)(s c), where s = (a + b + c)/2.

Racket Style Guide Fall 2017

CS115 - Module 8 - Binary trees

CS2500 Exam 2 Fall 2011

Getting started with C++ (Part 2)

The Design Recipe Fall 2018

Downloaded from Chapter 2. Functions

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Intro. Scheme Basics. scm> 5 5. scm>

Local defini1ons. Func1on mul1ples- of

Trees. Binary arithmetic expressions. Visualizing binary arithmetic expressions. ((2 6) + (5 2))/(5 3) can be defined in terms of two smaller

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Trees. Example: Binary expression trees. Example: Evolution trees. Readings: HtDP, sections 14, 15, 16.

Java is an objet-oriented programming language providing features that support

Text Input and Conditionals

CSc 372. Comparative Programming Languages. 36 : Scheme Conditional Expressions. Department of Computer Science University of Arizona

Trees. Readings: HtDP, sections 14, 15, 16.

CS 135 Fall 2018 Final Exam Review. CS 135 Fall 2018 Final Exam Review 1

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

How to Design Programs

Graphs. Readings: Section 28. CS 135 Fall : Graphs 1

Organization of Programming Languages CS3200/5200N. Lecture 11

Modern Programming Languages. Lecture LISP Programming Language An Introduction

6.001 Notes: Section 15.1

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

CS 115 Lecture Notes Winter 2019

CSc 520 Principles of Programming Languages

Functional Programming Languages (FPL)

Module 9: Binary trees

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Limits. f(x) and lim. g(x) g(x)

ü 1.1 Getting Started

2.4 Multiplication and Division of Integers

Graphs. Directed graphs. Readings: Section 28

CS 1110: Introduction to Computing Using Python Loop Invariants

Documentation for LISP in BASIC

How to Design Programs Languages

Introduction to Scheme

Basic types and definitions. Chapter 3 of Thompson

A Brief Introduction to Scheme (I)

Conditional Expressions and Decision Statements

Functions with Parameters and Return Values

Generative and accumulative recursion. What is generative recursion? Example revisited: GCD. Readings: Sections 25, 26, 27, 30, 31

CMSC 330: Organization of Programming Languages. Operational Semantics

Lecture 3: Recursion; Structural Induction

Administrivia. Simple data types

Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Chapter 1. Fundamentals of Higher Order Programming

Scheme Quick Reference

Homework 6: Higher-Order Procedures Due: 10:00 PM, Oct 17, 2017

Functional Programming. Pure Functional Programming

Typed Racket: Racket with Static Types

SPARK-PL: Introduction

(Provisional) Lecture 08: List recursion and recursive diagrams 10:00 AM, Sep 22, 2017

Conditionals !

CS 314 Principles of Programming Languages. Lecture 16

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

User-defined Functions. Conditional Expressions in Scheme

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

Language Reference Manual

Selection Statement ( if )

CS 11 Ocaml track: lecture 2

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

Racket: Modules, Contracts, Languages

Logical and Bitwise Expressions

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

Logical and Bitwise Expressions

Tracking Rumors. Suppose that we want to track gossip in a rumor mill

Welcome to CS 135 (Fall 2018)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

University of Massachusetts Lowell

Transcription:

Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, sections 4-5

Booleans (Bool) <, >, and = are new functions, each of which produces a boolean value (Bool). (< 4 6) (> 4 6) (= 5 7) Each produces #true or #false. These are the only values a Bool may take. (You may see #true called true or #t, and see #false called false or #f.) Note: keep track of order! < a b corresponds to a < b. A function which produces a Bool is called a predicate. Often the name of predicates end with?, as in string=? Other predicates include even? and odd?

Who cares?!? Conditionals 2 1 A sin-squared window, used in signal processing, can be described by 0 for x < 0 f (x) = 1 for x 1 sin 2 (xπ/2) for 0 x < 1 0 1 0 1 2 Racket gives us an easy way to design such things in a special form called cond. 1

Using cond to describe cases 0 for x < 0 f (x) = 1 for x 1 sin 2 (xπ/2) for 0 x < 1 (define (ssqw x) [(< x 0) 0] [(>= x 1) 1] [(< x 1) (sqr (sin (* x pi 0.5)))] )) cond is a special form, not a function. We deal with it in a special way. In particular, do not evaluate its arguments until necessary. Each argument of cond is a pair of square brackets around a pair of expressions: question answer.

Evaluating a cond statement How do we evaluate a cond? Informally, evaluate a cond by considering the question/answer pairs in order, top to bottom. When considering a question/answer pair, evalute the question. If the question evaluates to true, the whole cond takes the answer. (define (ssqw x) [(< x 0) 0] [(>= x 1) 1] [(< x 1) (sqr (sin (* x pi 0.5)))] )) For example consider, (ssqw 4). [(< 4 0) 0] [(>= 4 1) 1] [(< 4 1) (sqr (sin (* 4 pi 0.5)))] )

Problem solving with cond (define (ssqw x) [(< x 0) 0] [(>= x 1) 1] [(< x 1) (sqr (sin (* x pi 0.5)))] )) Use cond to write a function (absolute-value n) which produces n. (There is a built-in function abs which does this, but don t use it now.) a(n) = { n if n < 0 n if n 0 (define (absolute-value n) [(< n 0) (- n)] [(>= n 0) n] ))

No satisfied questions What happens if none of the questions evaluate to true? (define (absolute-value n) [(> n 0) n] [(< n 0) (- n)] )) An error occurs with this (absolute-value 0). This can be helpful if we try to consider all the possibilities, but we miss one, testing may raise this error. Then we can fix it. But sometimes we want to only describe some conditions, and do something different if none of them are satisfied.

else We could use a question which always evalutes to true: (define (absolute-value n) [(> n 0) n] [true (- n)] )) Remember: the question/answer pairs are considered in order, top to bottom, and it stops as soon as it finds a question which evaluates to true. This is useful sufficiently frequently that there is special keyword for it: else. (define (absolute-value n) [(> n 0) n] [else (- n)] ))

Tracing cond Recall we are imagining interpreting our programs as a series of substitutions, called a trace. How do we trace cond? The general form of a conditional is [question1 answer1] [question2 answer2]... [questionk answerk]) To evaluate the conditional, evaluate question1, then perform the following substitutions: [false exp0][exp1 exp2]...) [exp1 exp2]...) [true exp0][exp1 exp2]...) exp0 [else exp0]) exp0

Tracing cond example [false exp0][exp1 exp2]...) [exp1 exp2]...) [true exp0][exp1 exp2]...) exp0 [else exp0]) exp0 (define (ssqw x)...) (ssqw 0) [(< 0 0) 0] [(>= 0 1) 1] [(< 0 1) (sqr (sin (* 0 pi 0.5)))]) [false 0] [(>= 0 1) 1] [(< 0 1) (sqr (sin (* 0 pi 0.5)))]) [(>= 0 1) 1] [(< 0 1) (sqr (sin (* 0 pi 0.5)))]) [false 1] [(< 0 1) (sqr (sin (* 0 pi 0.5)))]) [(< 0 1) (sqr (sin (* 0 pi 0.5)))]) [true (sqr (sin (* 0 pi 0.5)))]) (sqr (sin (* 0 pi 0.5))) (sqr (sin 0)) (sqr 0) 0

Tracing cond (define (qux a b) [(= a b) 42] [(> a (+ 3 b)) (* a b)] [(> a b) (- b a)] [else -42])) (qux 5 4) Perform a complete trace of this program.

Testing cond You should write tests so each question is evaluated to true at least once, to verify each answer is tested. Include tests for boundaries; it is easy to get off-by-one errors! Suppose I wanted a function which produces 0 for negative numbers, 1 for positive numbers 10 or less, and 2 for other numbers. What should I test? I should check boundaries ( 1, 0, 1) and (10, 11), some other negative number, and some larger number. categorize.rkt

and now for something completely different We combine predicates using the special forms and, r, and the function not. These all consume and produce Bool values. and produces false if at least one of its arguments is false, and true otherwise. or produces true if at least one of its arguments is true and false otherwise. not produces true if its argument is false, and false if its argument is true. A few examples: (and (> 5 4) (> 7 2)) true (or (> 5 4) (> 7 2)) true (and (> 5 4) (< 7 2)) false (or (> 5 4) (> 7 2)) true (not (= 5 4)) true

An important subtlety interpreting and and or: short-circuiting and and or are not functions. They are special forms. Do not evaluate their arguments until necessary. Informally, evaluate the arguments one by one, and stop as soon as possible. For example: (define (baz x) (and (not (= 0 x)) (> 0 (cos (/ 1 x))))) If I run (baz 0), attempting to evaluate the expression (/ 1 x), would cause a division by zero error. But when x is zero, the first argument of and is false, so the second is not evaluated.

Substitution rules for and Use the following rules for tracing and: (and true exp...) (and exp...) (and false exp...) false (and) true Note: this is not what the stepper does! If in this course you are asked to perform a trace, follow these rules. Perform a trace of (and (= 3 3) (> 7 4) (< 7 4) (> 0 (/ 3 0))) (and true (> 7 4) (< 7 4) (> 0 (/ 3 0))) (and (> 7 4) (< 7 4) (> 0 (/ 3 0))) (and true (< 7 4) (> 0 (/ 3 0))) (and (< 7 4) (> 0 (/ 3 0))) (and false (> 0 (/ 3 0))) false

Substitution rules for or Use the following rules for tracing or: (or true exp...) true (or false exp...) (or exp...) (or) false Note: this is not what the stepper does! If in this course you are asked to perform a trace, follow these rules. Perform a trace of (or (< 7 4) (= 3 3) (> 7 4) (> 0 (/ 3 0))) (or false (= 3 3) (> 7 4) (> 0 (/ 3 0))) (or (= 3 3) (> 7 4) (> 0 (/ 3 0))) (or true (> 7 4) (> 0 (/ 3 0))) true

Nested Conditionals A museum offers free admission for people who arrive after 5 pm. Otherwise, the cost of admission is based on a person s age: age 10 and under are charged $5 and everyone else is charged $10. Write a function admission which produces the admission cost. It consumes two parameters: a Bool, after5?, and a positive integer, age.

Flattening Nested Conditionals Sometimes it is desirable to flatten the conditionals. ;; admission: Bool Nat -> Nat (define (admission after5? age) [after5? 0] [else [(<= age 10) 5] [else 10] ) (define (admission after5? age) [after5? 0] [(and (not after5?) (< age 11)) 5] [else 10])) (define (admission after5? age) [after5? 0] [(< age 11) 5] [else 10]))

Uses of cond Conditionals can be used like any other expression: (define (add-1-if-even n) (+ n [(even? n) 1] [else 0]))) (or (= x 0) [(positive? x) (> x 100)] [else (< x -100)]))

Black-box and white-box testing In science, computing, and engineering, a black blox is a device... which can be viewed in terms of its inputs and outputs, without any knowledge of its internal workings. (Wikipedia) Black-box testing refers to testing without reference to how the program works. Black-box tests should be written before you write your code. Your examples are black-box tests. A white box is a subsystem whose internals can be viewed but usually not altered. (Wikipedia) White-box testing should exercise every line of code. Design a test to check both sides of every question in every cond. These tests are designed after you write your code, by looking at how the code works.

Developing a Predicate I wish to develop a predicate cat-start-or-end?, which consumes a Str and determines if the Str starts or ends with "cat".

A data type for symbols: Sym A symbol is written as a tick followed by the name of the symbol, which follows the same rules as for identifiers (no spaces, some restrictions on characters). I can represent the four suits using the four symbols diamonds for diamonds, clubs for clubs, hearts for hearts, and spades for spades.

Operations on Sym A Sym is an indivisible, atomic value. The only operation that is possible is symbol=?, which checks if two symbols are equal. (define trump-suit hearts) (define (trump? suit) (symbol=? suit trump-suit))

When to use Sym and Str When should we use Sym? Any time you have a fixed set of items, and don t need to manipulate them or order them. When you are doing many equality comparisons. symbol=? is faster than string=? When shouldn t we use Sym? Any time you want to operate on items in any way. Any time you want to put items in order.

Problems with the contract Consider the following function: ;; check-divide: Num ->??? (define (check-divide n) [(= 0 n) "undefined"] [else (/ 1 n)])) What should the contract be? It could be a Num or a Str (specifically, "undefined"). Use anyof for situations like this. ;; check-divide: Num -> (anyof Num Str)

Generalized even gen-even? consumes an integer, a symbol, or a string, and produces true if the input is even, "even", or an even integer, and false otherwise. (gen-even? v) produce true if v is even, "even", or an even integer. Write the contract for gen-even? Design examples and tests for gen-even? Write the body of the function gen-even?

Checking the type of a value There s a problem when we go to write the body. We don t know what type v is. Built-in predicates to the rescue! number?, integer?, symbol?, and string? each have one parameter, and indicate if the value is a Num, Int, Sym, and Str respectively. Write the body of the function gen-even?

Generalized equality checking The built-in predicate (equal? a b) produces true if a, b are the same type, and if they have the same value. This is very handy if things may not be the same type. Rewrite gen-even? using equal?

Module summary Become comfortable using cond expressions, and, or, and not. Remember how to test these expressions, and know what black-box and white-box testing are. Make sure you understand short-circuiting in and and or. Become skillful at tracing code which includes cond, and, and or. Be able to write programs using Sym. Understand the use of anyof and be able to use it in your programs. Before we begin the next module, please Read How to Design Programs, sections 6-7, omitting 6.2, 6.6, 6.7, and 7.4.