Part 4 - Write Some Scheme

Problem 17

Implement the enumerate procedure, which takes in a list of values and returns a list of two-element lists, where the first element is the index of the value, and the second element is the value itself.

scm> (enumerate '(3 4 5 6))
((0 3) (1 4) (2 5) (3 6))
scm> (enumerate '())
()

Solution:

;; Returns a list of two-element lists
(define (enumerate s)
  ; BEGIN PROBLEM 17
      (define (make-enumerate lst index)
        (if (null? lst)
            nil
            (cons (list index (car lst)) (make-enumerate (cdr lst) (+ index 1))))
        )(make-enumerate s 0)
      )
  ; END PROBLEM 17

Problem 18

Implement the zip procedure, which takes in a list of two element pairs, and returns a new list where the first element is a list containing the first element of each pair and the second element contains the second element of each pair.

scm> (zip '((1 2) (3 4) (5 6)))
((1 3 5) (2 4 6))
scm> (zip '((1 2)))
((1) (2))
scm> (zip '())
(() ())

Solution:

(define (zip pairs)
  ; BEGIN PROBLEM 18
    (define (zipped-tail pairs lst)
             (if (null? pairs)
                 lst
                 (zipped-tail (cdr pairs)
                 (list
                (append (car lst) (list (car (car pairs))))
                (append (car (cdr lst)) (cdr (car pairs)))             
                    )
                )
             )
         )(zipped-tail pairs '(() ()))
  )
  ; END PROBLEM 18

Problem 19

This was a funny one. :)

Specs: https://inst.eecs.berkeley.edu/~cs61a/su19/proj/scheme/#problem-19-3-pt

Solution:

(define (let-to-lambda expr)
  (cond ((atom? expr)
         ; BEGIN PROBLEM 19
         expr
         ; END PROBLEM 19
         )
        ((quoted? expr)
         ; BEGIN PROBLEM 19
         expr
         ; END PROBLEM 19
         )
        ((or (lambda? expr)
             (define? expr))
         (let ((form   (car expr))
               (params (cadr expr))
               (body   (cddr expr))) ; BEGIN PROBLEM 19
           (append `(,(let-to-lambda form) ,(map let-to-lambda params)) (let-to-lambda body))
           ; END PROBLEM 19
           ))
        ((let? expr)
         (let ((values (cadr expr))
               (body   (car(cddr expr))))
           ; BEGIN PROBLEM 19
           'replace-this-line
           (define zipped-vals (zip values))
           (define params (car zipped-vals))
           (define args (car (cdr zipped-vals)))
           
           (append `((lambda ,( map let-to-lambda params)
            ,(let-to-lambda body)
         
           ; END PROBLEM 19
           )) (let-to-lambda args))
       ))
        (else
         ; BEGIN PROBLEM 19
         (map let-to-lambda expr)
         ; END PROBLEM 19
         )))

Last updated