Higher-Order Programming » Lab Sessions

Session 7

Assistant: Steven Keuchel (steven.keuchel@vub.be)

Section 1: Scheme Objects

Exercise 1: The Flip Procedure

  1. Define a procedure flip (with no parameters) that returns 1 the first time it is called, 0 the second time it is called, 1 the third time, 0 the fourth time, and so on.
  2. Define a procedure make-flip that can be used to generate flip procedures. That is, we should be able to define flip as (define flip (make-flip)).
  3. Draw an environment diagram to illustrate the result of evaluating the following sequence of expressions.




Exercise 2: A Turnstile

Create a Scheme object (see bank account example in the theory) that implements the behaviour of a turnstile (e.g., the barriers found at metro stops, the resto...). They count the number of persons that pass a specific point.

They should support the following operations.

The following boilerplate code is given.





Draw the environment diagram of executing the following sequence of expressions.





Exercise 3: Function Profiling

In software-testing applications, it is useful to be able to count the number of times a given procedure is called during the course of a computation. Write a procedure make-monitored that takes as input a procedure f, that takes itself one input. The result returned by applying make-monitored is a third procedure, say mf, that keeps track of the number of times it has been called by maintaining an internal counter. If the input to mf is the special symbol 'how-many-calls?, then mf returns the value of the counter. If the input is the special symbol 'reset-count! then mf resets the counter to zero. For any other input, mf returns the result of applying f on that input and increments the counter. For instance, we could make a monitored version of the sqrt procedure:





What happens when you call a monitored version of a recursive definition of fib.





Did your implementation return 1? Or another number? Adapt your solution. (Hint! You don't need to change make-monitored. You have to find a way to redefine fib.)

Exercise 4: A Turnstile Extension

Extend the implementation for turnstile of exercise 2 with the following features.