0704.315 Programming Languages

Homework 2


Due Date

Section 1: Wednesday Oct 17, 18:30
Section 2: Wednesday Oct 17, 12:30

Form of Submission

Homework can submitted via email or printout by deadline.

Assignment

This assignment will make you familiar with the list-processing style.
  1. Using the following implementation of positive integers:
         (define zero '())
         (define (zero? n) (null? n))
         (define (add1 n) (cons 'a n))
         (define (sub1 n) (cdr n))
         
    Restricting yourself to the interface (zero, zero?, add1, sub1), provide definitions for the following:
    1. [2 pts] The value one
      (define one (add1 zero))
      
    2. [4 pts] The binary addition procedure, i.e.,
      	(define (add a b)
      	  ;; insert body here
              )
           
           (define (add a b)
             (if (zero? b)
      	   a
      	   (add (add1 a) (sub1 b))))
      
    3. [4 pts] The binary subtraction procedure
           (define (subtract a b)
             (if (zero? b)
      	   a
      	   (subtract (sub1 a) (sub1 b))))   
        
  2. [5 pts] What is the difference between the following two Scheme definitions?
    	(define (increment n) (+ n 1))
         
    	(define increment (lambda (n) (+ n 1)))
         

    There is no difference in meaning, just in syntax.

    
         
  3. The next few questions will use the following procedure:
    	(define (accumulate op init r)
    	    (if (null? r)
    		init
    		(op (first r) (accumulate op init (rest r)))))
    	
    1. [2 pts] What is value of (accumulate + 0 '(1 2 3 4)) ?

      10

    2. [2 pts] What is value of (accumulate - 0 '(1 2 3 4)) ?

      -2

    3. [2 pts] What is value of (accumulate * 0 '(1 2 3 4)) ?

      0

    
    
    
  4. [4 pts] Using accumulate and the following binary operator, write a procedure that takes a list of any number of elements and multiplies them all together
    	(define (product a b)
    	    (if (= a 1)
    		b
    		(+ b (product (- a 1) b))))
    	
    (define (*list li)
      (accumulate product 1 li))
    
    
    
    
  5. [10 pts] Write a definition for list-append (as seen last homework) in terms of accumulate.
    (define (list-append l1 l2)
      (accumulate cons l2 l1))
    
    
  6. [10 pts] Write a definition for list-length (as seen last homework) in terms of accumulate.
    (define (list-length li)
      (accumulate (lambda (a b) (+ 1 b)) 0 li))