Search code examples
lambdaschemeracketevaluationoperator-precedence

Evaluation order for the expression ((lambda (x) (* x 2)) (+ 3 1))?


A

((lambda (x) (* x 2)) (+ 3 1))
((lambda (x) (* x 2)) 4)
(* 4 2)
8

B

((lambda (x) (* x 2)) (+ 3 1))
(* (+ 3 1) 2)
(* 4 2)
8

I guess there are 2 versions. But I'm not sure which one is correct.


Solution

  • The second one uses what SICP calls substitution. It isn’t what real lisps do, it’s described as a learning exercise in chapter 1. Once special forms like let get introduced this doesn’t work.

    The first one uses applicative order and is what a real scheme implementation like racket does. It evaluates the lambda, then evaluates the following expression, then applies the function resulting from the lambda to the result of evaluating (+ 3 1).

    This is how Gerald Sussman explains his use of the substitution model:

    If we're going to understand processes and how we control them, then we have to have a mapping from the mechanisms of this procedure into the way in which these processes behave. What we're going to have is a formal, or semi-formal, mechanical model whereby you understand how a machine could, in fact, in principle, do this. Whether or not the actual machine really does what I'm about to tell you is completely irrelevant at this moment.

    In fact, this is an engineering model, in the same way that, [for an] electrical resistor, we write down a model V = IR — it's approximately true, but it's not really true; if I put enough current through the resistor, it goes boom, so the voltage is not always proportional to the current, but for some purposes the model is appropriate.

    In particular, the model we're going to describe right now, which I call the substitution model, is the simplest model that we have for understanding how procedures work and how processes work — how procedures yield processes.

    And that substitution model will be accurate for most of the things we'll be dealing with in the next few days. But eventually, it will become impossible to sustain the illusion that that's the way the machine works, and we'll go to other, more specific and particular models that will show more detail.