I am having trouble with some tricky-looking lambda expressions in Scheme, and I would like to see how they are being evaluated by the interpreter.
I would like the Scheme interpreter to print all the evaluation steps, as seen in SICP Section 1.1.5, “The Substitution Model for Procedure Application”.
I am looking for a solution using any Scheme interpreter. I have already tried Racket’s tracing, but it only traces procedure calls, not every expression.
Motivating example
Given the definition of Church numerals from SICP Exercise 2.6:
(define zero (lambda (f) (lambda (x) x)))
(define (add-1 n)
(lambda (f) (lambda (x) (f ((n f) x)))))
and the task:
Define
oneandtwodirectly (not in terms ofzeroandadd-1).
I wish to check my definitions of one and two against the results of evaluating (add-1 zero) and (add-1 (add-1 zero)).
This is what I would like the Scheme interpreter to print out:
> (add-1 zero)
(add-1 (lambda (f) (lambda (x) x)))
(lambda (f) (lambda (x) (f (((lambda (f) (lambda (x) x)) f) x))))
(lambda (f) (lambda (x) (f ((lambda (x) x) x))))
(lambda (f) (lambda (x) (f x)))
>
This is very easy with combinators-like equations (what was once called applicative style I believe )
With combinators, everything is curried:
a b c dis actually(((a b) c) d)anda b c = dis equivalent to(define a (lambda (b) (lambda (c) d))).Now it is clear what is the intended meaning of
fandx:xstands for a concrete implementation of “zero” data element, andfstands for a concrete implementation of “successor” operation, compatible with a given concrete implementation of “zero”.fandxshould have really be named mnemonically:Not so tricky-looking anymore, with more convenient syntax, right?
lambdaitself was a typographical accident anyway. Now,Tracing the steps according to the SICP 1.1.3 combinations evaluation procedure,
and the 1.1.5 sustitution model for procedure application
we get
and here the substitution stops actually, because the result is a simple lambda expression, i.e. not a combination. Only when two more arguments are supplied, the evaluation is done in full:
and then the calculation will proceed according to the actual definitions of
sandz. That is what the equations (1) shown above indicate, in shorter notation.