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
#trueor#false); or - An image
And we know several built-in functions, for example:
- Arithmetic functions like
+,-,logand so on; - String functions like
string-append,string->numberand 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 2 to its argument
(check-expect (add2 3) 5)
(define (add2 x)
(+ x 2))- Making decisions
- Doing things over and over again
- Use
place-imageandempty-sceneto write a function that places a circle in a blank scene of size 200 x 160 at a position halfway up and at a given distance from the left side.
Don't forget
(require 2htdp/image)Here's the template for you (I'll explain later why it's called moving-ball :
;; number -> image
;; Place a circle at a specified location in an empty scene
(check-expect (moving-ball 80)
(place-image
(circle 10 "solid" "red")
80 80
(empty-scene 200 160)))
(define (moving-ball x)
... )- Replace magic numbers with constants
For example,
(define BALL-RADIUS 40)- Make the ball move from left to right using
animate.
(if (> 3 2) 3 2)or
(cond
[(> 3 2) "three is bigger than two!"]
[(< 3 2) "two is bigger than three!"]
[else "three is the same size as two!"])-
Write a function
biggestwhich, given two numbers, returns the larger of the two, eg(biggest 3 2)should produce 2.(This function already exists: it is called
max.) -
Write a function
income-taxwhich computes your income tax given a gross salary. The rule is as follows (this is slightly simplified)- Up to £11,500 : 0% (Personal allowance)
- £11,501 - £45,000 : 20% (Basic rate)
- £45,001 - £150,000 : 40% (Higher rate)
- over £150,001 : 45% (Additional rate)
Hint: To start with, imagine there is only the personal allowance and the basic rate (no other tax brackets). Try to make that work.
Hint: It will be easier to define auxiliary functions that each do some part of the work.
Hint: You could also write a cond that starts at the top and works downwards.
- Let's talk about
worldprograms.