Scheme: basic-level questions

If you need help reviewing Scheme, take a look at these resources:

Each question has a "Toggle Solution" button -- click it to reveal that question's solution.

What would Scheme print

Question 1

scm> (+ 4 3)
______
scm> (4 + 3)
______
scm> (+ 1 2 3 4)
______
scm> (- 1 2 3 4)
______

Question 2

scm> (if True (+ 2 3))
______
scm> (if False (+ 2 3))
______
scm> (if False (/ 1 0) 4)
______
scm> (and True False True)
______
scm> (and True 0 True)
______
scm> (and 3 5 2)
______
scm> (or True False True)
______
scm> (or False 4 True)
______

Question 3

scm> (define x 2)
______
scm> x
______
scm> (define (f x) (* x x))
______
scm> (f 4)
______
scm> (define (g x) (lambda (y) (* x y)))
______
scm> ((g 4) 5)
______

Question 4

scm> (cons 1 (cons 2 nil))
______
scm> (cons 1 2)
______
scm> (car (cons 1 (cons 2 nil)))
______
scm> (cdr (cons 1 (cons 2 nil)))
______
scm> (cdr (cons 1 2))
______
scm> (null? (cons 1 nil))
______
scm> (null? (cdr (cons 1 nil)))
______
scm> (list 1 2 3 4)
______
scm> (cdr (list 1 2 3 4))
______

Code-Writing Questions

Question 5

Implement the function filter, which takes a predicate and a Scheme list as arguments. filter will return a new list that only contains elements of the original list that satisfy the predicate.

(define (filter pred lst)
    ; YOUR CODE HERE
    )

; Tests
scm> (define (less-3 x) (< x 3))
less-3
scm> (filter less-3 (list 1 2 3 4))
(1 2)
(define (filter pred lst)
    (cond ((null? lst) nil)
          ((pred (car lst)) (cons (car lst)
                                  (filter pred (cdr lst))))
          (else (filter pred (cdr lst)))))

Question 6

Implement the function interleave, which takes a two lists as arguments. interleave will return a new list that interleaves the elements of the two lists, with list1 starting first. Refer to the tests for sample input/output.

(define (interleave list1 list2)
    ; YOUR CODE HERE
    )

; Tests
scm> (interleave (list 1 3 5) (list 2 4 6))
(1 2 3 4 5 6)
scm> (interleave (list 1 3 5) nil)
(1 3 5)
scm> (interleave (list 1 3 5) (list 2 4))
(1 2 3 4 5)
(define (interleave list1 ist2)
    (if (or (null? list1) (null? list2))
        (append list1 list2)
        (cons (car list1)
              (cons (car list2)
                    (interleave (cdr list1) (cdr list2))))))

Question 7

Implement the function count-stairways, which takes a number (of steps). Assuming we can take 1 or 2 steps, return the number of ways we can climb up the stairs.

(define (count-stairways n)
    ; YOUR CODE HERE
    )

; Tests
scm> (count-stairways 4)
5
scm> (count-stairways 5)
8
(define (count-stairways n)
    (cond ((= n 1) 1)
          ((= n 2) 2)
          (else (+ (count-stairways (- n 1))
                   (count-stairways (- n 2))))))