CS212 Exams
Spring 1998 -
Final

Fun with Higher-Order Functions


Often when I'm debugging Scheme code, it's useful to insert a print statement before and after a function is executed. For instance, suppose f is a function that takes one argument. I might write:

(define debugging #t)

(define (debug-f x)
  (when debugging (print "executing f"))
  (let ((result (f x)))
    (when debugging (print "done executing f"))
    result))

Now I can call debug-f when I'm in debugging mode. To turn off the extra output, I can just set! the variable debugging to false.

Of course, if I want to debug another function, then I'm going to have to essentially duplicate the code. Being a good (i.e., lazy) programmer, I prefer to pull out the common stuff into a single higher-order definition.

  1. Write a function make-debug which takes a function fun of one argument and a string name, and returns a new "debug" version of the function. For example, calling (make-debug f "f") should return a function that is equivalent to debug-f defined explicitly above.




  2. Sometimes I like to profile my code to find out where it's spending time. Suppose we have a function gettime which takes no arguments and returns the current time as a string. For instance:
    ==> (gettime)
    "3:35:02pm"
    ==> (gettime)
    "3:35:05pm"

    Write a function make-profile which, similar to make-debug, takes a function fun and returns a function which when given an argument x, runs fun on x and prints out the start and end time if the variable profiling is true.





Solution

Return to CS 212 Final - Spring 1998