Recap
Expressions are like little questions for Racket to answer. We have seen two ways to make expressions. An expression is either:
-
A value; or
-
(
function expression1 expression2 ...)
The value of the first kind of expression is itself. To evaluate the second kind of expression, Racket first evaluates all the sub-expressions, then applies the function to the values produced.
We also now know several kinds of value. A value is either:
- A number (
42
); - A string (
"Hello, World."
); - A "Boolean" (either
#true
or#false
); or - An image
And we know several built-in functions, for example:
- Arithmetic functions like
+
,-
,log
and so on; - String functions like
string-append
,string->number
and so on; - Boolean functions like
and
,or
, andnot
; and - Image functions like
circle
.
And we have seen examples of defining new functions and new "global constants". For example:
(define THE-ANSWER 42)
(= (* 6 7) THE-ANSWER)
;; Number -> Number
;; Adds 1 to its argument
;; eg, (add1 3) should be 4
(define (add1 x)
(+ x 1))
- Complete this function definition by replacing the "..." with the right expression:
;; Number -> Number
;; Convert a distance in inches to centimetres
;; eg, (inches->cm 1) should be 2.54
(define (inches->cm length)
... )
- Define
feet->inches
, that converts feet into inches:
;;; Number -> Number
;; Convert a distance in feet to one in inches
;; eg, (feet->inches 1) should be 12
(define ... )
-
Design a function
feet->cm
using the functionsfeet->inches
andinches->cm
. -
Define a constant called
CM/INCH
whose value is 2.54 and replace 2.54 in the defintion ofinches->cm
with this constant. -
Exercise with strings
;; String -> String
;; Add "Hello, " to a given name
(check-expect (greet "James") "Hello, James")
(check-expect (greet "Tomás") "Hello, Tomás")
(define (greet name)
...)
-
Go back to the conversion functions and replace the examples in comments with
check-expect
.
;; Number Number -> String
;; Convert a distance in feet and inches to centimetres
(check-expect (feet/inches->cm 5 7) 170.18)
(define (feet/inches->cm ft in)
... )
;; Number -> Image
;; Draw a tree of the given height
(define (tree height)