Lecture 3 : Moving Beyond Numbers (Clash the Symbols!)
Recap: Steps to develop programs with conditions:
1. contract, purpose, header
3. develop examples
5. body (write the cond questions first, then fill in the answers)
6. test
A dorm survey determines that if slices are less than $1, students
collectively eat 50 slices. If slices are at most $1, but no more than
$1.50, students eat 34 slices. If slices are more than $1.50, students
only eat 21 slices. Write a program order, which determines how many
pizzas to order based on the cost of a slice (assume a pizza has 8 slices).
;; order : num -> num
;; calcuate how many pizzas to order based on the price
(define (order price)
(cond [(<= price 1) (num-pizzas 50)]
[(and (< 1 price) (<= price 1.5)) (num-pizzas 34)]
[else (num-pizzas 21)]))
;; test cases
; (order .50) = 7
; (order 1) = 7
; (order 1.25) = 5
; (order 1.5) = 5
; (order 2) = 3
;; num-pizzas : num -> num
;; calculate how many pizzas are needed to cover the number of slices
(define (num-pizzas slices)
(ceiling (/ slices 8)))
;; test cases
; (num-pizzas 8) = 1
; (num-pizzas 14) = 2
Let's move beyond numbers. Often, we want to compute over data other than
numbers. People who study language processing, for example, need a way to
represent words. In Scheme, we represent words using symbols. A symbol
resembles a word, but has a quote mark on the front and can contain
characters other than letters (but no spaces):
'kathi 'Rice 'comp210 'class-of-2003
What operations can we perform on symbols? Does (+ 'kathi 3) make
sense? No, because 'kathi isn't a number. The only thing we can do
with symbols is compare them for equality. We do this using an
operator called symbol=?:
(symbol=? 'kathi 'kathi) = true
(symbol=? 'kathi 'john) = false
(symbol=? 'kathi 'Kathi) = false
Write a program babel that takes the name of a language and produces
the word for hello in that language if the language is spanish,
french, or pig-latin. The program produces 'hello for any other
language.
;; babel : symbol -> symbol
;; translate hello into the given language
(define (babel lang)
(cond [(symbol=? lang 'spanish) 'hola]
[(symbol=? lang 'french) 'bonjour]
[(symbol=? lang 'pig-latin) 'ellohay]
[else 'hello]))
;; test-cases
; (babel 'spanish) = 'hola
; (babel 'french) = 'bonjour
; (babel 'pig-latin) = 'ellohay
; (babel 'esperanto) = 'hello