
Scheme |
|
| Q: |
How do I insert debugging print statements in a Scheme program? |
| A: |
The display function takes a single parameter
and prints its value at the time it is executed.
Unlike any other function we have studied in Scheme,
this function has a side effect. In fact, the
only reason to execute display is to have that
side-effect: The value returned by the function is
useless. To start printing on a new line, use
newline. You can put these together in a simple
function that prints all its arguments on one line:
(define print-all
(lambda (ls)
(map display ls)
(newline)))
The resulting function will take a list of arguments
and print them on a single line:
> (define a '(1 2 3)) > (define b '(4 5)) > (print-all (list "hello " a b)) hello (1 2 3)(4 5)Note that you only get a space between two values if you explicitly insert it. There's another feature you need to know if you're going to print values in any of the three clauses of an if. If you want to print debugging information in one of those clauses, you have to both call display to print the value and then actually do the required computation. How do you do two things in the same expression? Use the begin function. This evaluates all of its arguments in left-to-right sequence but only returns the value of the last one:
> (define ls '(1 2 3)) ; assume a and b defined as above
> (if (begin (print-all (list ls)) (null? ls))
(begin (print-all (list a)) a)
(begin (print-all (list b)) b))
(1 2 3)
(4 5)
(4 5)
Note that the last (4 5) is the printed result
of the if, whereas the first two lines are
side-effects resulting from calls to print-all
while the clauses of the if were executing.
|
| Q: |
What's the Scheme equivalent of % (the C/Java modulo operator)? |
| A: |
modulo. As in
> (modulo 5 2) 1 |
| Q: |
I'm getting tired of having to re-type my functions at the Chez prompt, and would really like to save my work in the file mywork.scm, which I can then load. How do I do this? |
| A: |
> (load "mywork.scm") |
| Q: |
Okay: how about something that will let me give names to interesting values (such as functions and lists) so that I don't have to keep typing them? |
| A: |
> (define mylist '(1 2 3 4 5 6 7 8 9)) > mylist (1 2 3 4 5 6 7 8 9) |
| Q: |
Cool. How do I exit Chez when I'm done? |
| A: |
> (exit) |
| Q: |
About car: in class lectures, we've
learned that car returns the first
element in a list, and cdr returns the
"rest of the list". So the expression (car '((1 2)
3)) ought to return 1. |
| A: | The key is to remember that lists are elements, too. car always gives you the contents of the address register in a cons cell. If this cell is the head of a list beginning with a number, you'll get a number; if the list begins with a sublist, the value returned by car will be the sublist itself (really, what you're getting is the list's address in memory). |
|
A couple of random finer points that have come to us as mail messages: |
|

