Why do we use sequence to expression conversion in lisp interpreters?

Viewed 70

I am reading SICP which uses Scheme dialect of lisp. My question is why is there a need for sequence to expression conversion function as defined below which is used in conditional definitions but isn't used in the if expressions?

(define (sequence->exp seq)
    (cond ((null? seq) seq)
          ((last-exp? seq) (first-exp seq))
          (else (make-begin seq))))

(define (make-begin seq) (cons 'begin seq))

Following is the definition of if expression which doesn't require sequence to expression conversion:

(define (if? exp) (tagged-list? exp 'if))
(define (if-predicate exp) (cadr exp))
(define (if-consequent exp) (caddr exp))
(define (if-alternative exp)
    (if (not (null? (cdddr exp)))
        (cadddr exp)
        'false))

(define (eval-if exp env)
  (if (true? (eval (if-predicate exp) env))
      (eval (if-consequent exp) env)
      (eval (if-alternative exp) env)))

Following is the definition of conditional whose predicate does require sequence to expression conversion.

(define (cond? exp) (tagged-list? exp 'cond))

(define (cond-clauses exp) (cdr exp))

(define (cond-else-clause? clause)
    (eq? (cond-predicate clause) 'else))

(define (cond-predicate clause) (car clause))

(define (cond-actions clause) (cdr clause))

(define (cond->if exp) (expand-clauses (cond-clauses exp)))

(define (expand-clauses clauses)
    (if (null? clauses) 
        'false ; no else clause
    (let ((first (car clauses))
         (rest (cdr clauses)))
        (if (cond-else-clause? first)
            (if (null? rest)
                (sequence->exp (cond-actions first))
                (error "ELSE clause isn't last: COND->IF"
                clauses))
            (make-if (cond-predicate first)
                     (sequence->exp (cond-actions first))
                     (expand-clauses rest))))))
1 Answers

An if expression can only evaluate either one consequent expression, or one alternate expression. But a cond expression evaluates a sequence of expressions associated with the conditional clause that is true. The sequence->exp procedure is needed to convert a sequence of expressions into a single expression. By wrapping the sequence in a begin form, a single expression is created which can be evaluated as a consequent or alternate expression in an if expression.

The purpose of the sequence->exp calls in the posted code is to facilitate the conversion of cond expressions to if expressions; consequently, any sequence of expressions found in a cond branch must be converted to a single expression in a newly minted if expression.

Related