Homework 4

This is the archived website of SI 413 from the Fall 2013 semester. Feel free to browse around; you may also find more recent offerings at my teaching page.

Many of these exercises are programming exercises, but you do not need to submit them electronically.

Scheme has a built-in function add1 which adds 1 to its argument.

But what if we wanted to create a similar function like add2 or add20? Write a function that produces a function make-adder that takes an argument n and produces a lambda expression (function) that takes one argument and adds n to it.

So for example ((make-adder 5) 10) produces 15.

# 2 To recurse or not to recurse

Given a list of 2-digit numbers, I want to know the largest digit that appears anywhere. For example:

(bigdigit (list 53 23 44 36 12)) ; should return 6
(bigdigit (list 5 81 53)) ; should return 8

Write two versions of the bigdigit function: one using recursion (like the last HW), and one using the new things we have learned like apply, map, and lambda.

Hint: for the non-recursive version, I recommend you write a lambda function that takes a 2-digit number and produces the largest digit in that number. Then use map with this lambda function, and finally pass that whole list to an apply call that uses the built-in max.

1. Recursive version

2. Non-recursive version

# 3 The Doubler

1. Write a function (double f) which takes a 1-argument function f and produces a 1-argument function (as a lambda expression) that takes an argument x and applies f to it twice, like (f (f x)).

So for example calling ((double sqrt) 16) is the same as calling (sqrt (sqrt 16)), which is 2.

2. Can we do (double double)? What does it do?

# 4 Pushups

A certain sports team scores points in varying increments (2, 3, 6, 7), and after each score, certain fans must perform a number of push-ups corresponding to the total score at that time.

Write a function (pushups points) that takes the points from the most recent score, and returns the total amount of push-ups that must be performed at that time. (You will need to use a global variable to hold the current score and the set! function to change it!)

For example, if we start with (pushups 3), the returned value is 3. But if the next call is (pushups 7), the returned value is 10, since that is the total score at that point.

# 5 Reverse order print

Write a function (print-reverse L) that takes a list L and prints its elements in reverse, one per line, and then returns (void).

For example, calling (print-reverse '(1 2 3)) should print

3
2
1

# 6 Pretty-print inches

Write a function (print-height inches) that takes a number of inches and prints the feet and inches nicely. For example, calling (print-height 70) should cause the following to be printed:

5 feet 10 inches

Once this works, make it nicer so that, for example (print-height 73) prints

6 feet 1 inch

(notice not inches) and (print-height 8) just prints

8 inches

and any other cases which seem sensible to you.