Metaprogramming

Course links

Exercise 1

Write a Scheme expression that, when evaluated, yields a datum that looks just like the following definition of the singleton? procedure:

(define singleton?
  (lambda (pair)
    (null? (cdr pair))))

Do not use quotation or quasiquotation, except immediately before a symbol.

Exercise 2

Consider the following family of procedures:

(define element-0
  (lambda (ls)
    (car ls)))

(define element-1
  (lambda (ls)
    (car (cdr ls))))

(define element-2
  (lambda (ls)
    (car (cdr (cdr ls)))))

(define element-3
  (lambda (ls)
    (car (cdr (cdr (cdr ls))))))

Define a procedure called fetcher that takes a natural number n as argument and returns a Scheme datum that looks just like the definition of the element-n procedure from this series.

> (fetcher 7)
(define element-7 (lambda (ls) (car (cdr (cdr (cdr (cdr (cdr (cdr (cdr ls))))))))))

Exercise 3

A projection function is a procedure that returns one of its arguments and ignores all of the others. Here, for instance, is the definition of a projection function that returns the next-to-last of its seven arguments:

(define position-5-of-7
  (lambda (p0 p1 p2 p3 p4 p5 p6)
    p5))

Write a procedure projection-function-maker that takes two arguments -- a positive integer argument-count and a natural number position that must be less than argument-count -- and returns a datum that looks just like the definition of a projection function that has argument-count arguments and returns the one in the specified (zero-based) position.

> (projection-function 7 5)
(define position-5-of-7 (lambda (p0 p1 p2 p3 p4 p5 p6) p5))

Exercise 4

The file /home/stone/courses/scheme/examples/record-builder.ss contains the definition of the generate-record-definition-file procedure from today's reading.

(a) Load this file into DrScheme and call the generate-record-definition-file procedure with appropriate arguments to construct the implementation of a shirt record type, with five fields: catalog number, size, color, price, and quantity in stock. (The procedure presupposes that all fields are mutable.)

(b) Inspect the file that generate-record-definition-file created in the preceding exercise; it will be called shirt-definition.ss.

(c) Load the shirt-definition.ss file and use the constructor procedure defined in it to create an inventory record for a shirt with catalog number 03862A, size XL, white, priced at $21.95, with six in stock.

Exercise 5

Puzzle (for entertainment only): Write a Scheme procedure call that, when evaluated, yields a datum that looks just like itself. Hint: Use a lambda-expression to express the procedure that will be invoked.