Comp 210 Lab 11: set!

set!, Input and output


set!

To change which thing a placeholder refers to, we use set!, as introduced in class. We'll review set! by example.

To do: Try evaluating the following examples. First try them in your head or on paper. Then try them in DrScheme to see if you were right.

To do: Develop factorial-count! : natnum -> number, which computes the factorial of its argument. It also keeps track of how many times the user has called in function, using the global variable factorial-count. It does not count any recursive calls, e.g.,

     > (factorial-count! 3)
     6
     > factorial-count
     1
     > (factorial-count! 5)
     120
     > factorial-count
     2
     
Ideally, we would want to hide the variable factorial-count, but still provide access to it somehow. Your homework has a problem similar to that.


Input and output

Since Scheme automatically displays the result of whatever expression we give it, so far we haven't needed to know how to display something ourselves. Here are a few functions for getting information into and out of our programs. Try them out.

printf debugging

So far, you have used two good techniques for debugging code:

Using printf appropriately can provide one more good technique, by displaying important pieces of information. The most common places to do this are at the beginning and/or end of functions.

The following version of factorial doesn't work:

     (define (buggy-factorial n)
         (cond [(zero? n) 1]
               [else      (* (sub1 n) (buggy-factorial (sub1 n)))]))

We will rewrite our code to print out the input(s) and output(s) of the function:

     (define debug? true)  ; do I want to display debugging info?

     (define (buggy-factorial n)
        (if debug? (printf "buggy-factorial input: ~s~n" n))
        (local [(define result
                    (cond [(zero? n) 1]
                          [else      (* (sub1 n) (buggy-factorial (sub1 n)))]))]
            (if debug? (printf "buggy-factorial output: ~s~n" result))
            result))
To do: Use this code to see what the printed messages look like.

There are several things to note here: