Labwork
finish this during section
Exercise 0.
Fire up the interpreter (click the link on the top of this page)
and try these out, starting from the left column:
(first 'hello) 'pi
(+ 2 3) '+
(first hello) (+ pi 7)
(+ 5 6 7 8) 'hello
(first (bf 'hello)) (* pi pi)
(+) '(+ 2 3)
(+ (first 23) (last 45)) (define (square x) (* x x))
(sqrt 16) '(good morning)
(define pi 3.14159) (square 5)
(+ (* 3 4) 5) (first 274)
pi (square (+ 2 3))
+ (butfirst 274)
What do you think the parens do? What do you think '
does?
What do you think define
does? Confirm with your TA.
Exercise 1.
Parens are very important in Scheme.
In order to call on a procedure to do something,
you MUST wrap the procedure in parens with its arguments,
or the data you want it to act on. For example, from above,
typing (+ 2 3)
into the interpreter outputs 5.
You can also include subexpressions in a procedure call
in order to do more complicated things, like (+ (* 3 4) 5)
.
However, parens don't always mean "call a procedure to do something".
More on this later.
a. Translate the arithmetic expressions
48÷(2×(9+3))
and
(48÷2)×(9+3)
into Scheme expressions. Type them into the interpreter to check.
You saw how to
define a square
procedure:
(define (square x) (* x x))
After defining, you can use the procedure square
to find the square of any number you want. Likewise...
b. Without using *
(use square
instead),
define a procedure sum-of-squares
, which takes two arguments,
and returns the sum of the squares of the two arguments.
Exercise 2.
We've shown you some interesting procedures that allow you to do stuff to
words:
'
makes a word or a group of words (in parens).
first
takes a word and returns the first letter of that word
butfirst
(or bf
) takes a word and returns everything but the first letter
Some terminology:
'pi
is an example of creating a word
'(good morning)
creates a group of words, or a sentence, representing "good morning"
Keep these procedures and concepts in the back of your mind.
They'll come back in later exercises and labs.
Write a function that takes a word and returns the second letter.
Exercise 3.
Scheme has some control features that allow you to choose what to do next
based on a test:
Some good procedures to use for the test are >, <, and =.
Also take a look at:
a. Take a moment to read through the references,
and try them out in the interpreter.
Then, write a procedure can-drive
that takes the age of a person as an argument.
If the age is below 16, return the sentence (not yet).
Otherwise, return the sentence (Good to go).
Make sure to test your code in the interpreter.
b. Write a procedure fizzbuzz
that takes a number
and outputs the word fizz
if the number is divisible by 3,
buzz
if it's divisible by 5, fizzbuzz
if it's divisible by both 3 and 5, and otherwise, the number itself.
You may find remainder
useful. Make sure to test your code in the interpreter.