On this page:
6.1 Some tests
6.2 Make a function
6.3 New match clauses in eval-exp
6.4 Done?
7.2

6 Functions

If we’ve been through the previous part, we can keep using the same file. Or we can use 3-definitions.rkt as our starting point.

Functions are good for parameterizing pieces of code.

A function in our language wil be built from a list of parameter names and a list of terms for the function body. When called, the function should extend its environment with its parameters bound to the arguments supplied by the caller, and then evaluate the body.

6.1 Some tests

You might want to copy them into the test module at the bottom of your Racket file. The tests are going to fail at first. By the end of this chapter they should pass.

(check-equal?
 (evaluate '((λ () (+ 2 3))))
 5)
(check-equal?
 (evaluate '((lambda (x y) (+ x y)) 3 4))
 7)
(check-equal?
 (evaluate
  '((lambda ()
      (define a 2)
      (define b 3)
      (+ a b))))
 5)
(check-equal?
 (evaluate
  '((lambda ()
      (define a 2)
      (define b (lambda (c) (define a 5) (+ a c)))
      (b a))))
 7)

6.2 Make a function

When eval-exp encounters a “lambda” we want to make a real Racket function.

We make make-function function:

(define (make-function env parameters body)
  (λ arguments
    your code here))

make-function returns a Racket-function (made with the λ). That function should extend the environment it was defined in with each parameter name bound to the corresponding argument-value, and then eval-sequence its body.

6.3 New match clauses in eval-exp

[(list 'λ parameters body ...) your code here]

When the 'λ matches we want to make a function with make-function.

Also, we will add a very similar match-clause, for when people use lambda instead of λ.

6.4 Done?

Run and see that all the tests pass.
Next is Continuation-passing style. We can keep using the Racket-file we’re working with, or skip to 4-functions.rkt.