Lab 8 - Scheme

In this part of the lab, we will be learning Scheme. We have provided a Javascript based scheme interpreter that will let you interpret Scheme right in your browser! You can type code into the boxes, and to run the interpreter, either click outside, or press Ctrl-Enter. Give it a try below:

(+ 1 2)

If you like the in-line interpreter, check out the Interactive SICP, where you can interpret Scheme expressions while you are reading the book.

Question 1: Abstraction with procedures

Fill in the definition for the procedure accumulate, as you have been asked to do in Homework 2:

Accumulate takes in:

  1. combiner: A function of two arguments

  2. start: A number to start combining with

  3. n: The number of terms to combine

  4. term: A function of one argument that computes the n-th term of the sequence.

And returns the result of combining the first n terms of the sequence.

(define (accumulate combiner start n term) (if (= n 0) start 'Your-Code-Here )) (define (square x) (* x x)) (accumulate + 0 4 square) ;; Computes 1^2 + 2^2 + 3^2 + 4^2 = 30

Question 2: Abstraction with data

Remember the tree data structure that we built in discussion.

(define (make-btree entry left right) (cons entry (cons left right))) (define test-tree (make-btree 2 (make-btree 1 nil nil) (make-btree 4 (make-btree 3 nil nil) nil))) ;; Represents: ; 2 ; / \ ; 1 4 ; / ; 3 (define (entry tree) (car tree)) (define (left tree) (car (cdr tree))) (define (right tree) (cdr (cdr tree)))
(entry test-tree) (entry (left test-tree)) (entry (right test-tree))

Write a procedure num-leaves, that counts the number of leaves in a tree.

(define (numLeaves tree) 'Your-Code-Here ) (numLeaves test-tree) ; Should return 2