Folding

Exercise 1

Using fold-list, develop a procedure concatenate that takes a list of strings as its argument and constructs and returns one long string formed by appending together all of the list elements. Here is one sample call (you'll want to write others):

> (concatenate (list "alpha" "beta" "gamma" "delta"))
"alphabetagammadelta"

Exercise 2

Determine and explain the effect of the procedure mystery-1, defined below, which takes any list as its argument.

(define mystery-1
  (fold-list (list null)
             (lambda (new recursive-result)
               (append recursive-result
                       (map (left-section cons new)
                            recursive-result)))))

Exercise 3

Determine and explain the effect of the procedure mystery-2, defined below, which takes any list of digit characters as its argument.

(define mystery-2
  (tail-fold-list 0 (lambda (new so-far)
                      (+ (* 10 so-far)
                         (- (char->integer new)
                            (char->integer #\0))))))

Exercise 4

Using the appropriate higher-order procedure from the reading, concisely define the wrap procedure described in exercise 7 of the lab on recursion with integers.

Exercise 5

In the reading, we saw that (tail-fold-list null cons) is the reverse procedure. What does (fold-list null cons) do?

Exercise 6

Using fold-natural, define and test a procedure harmonic that takes any natural number n and returns the nth harmonic number, which is the sum of the reciprocals of the positive integers less than or equal to n. (For instance, the fourth harmonic number is 1/1 + 1/2 + 1/3 + 1/4, or 25/12.)

Exercise 7

Determine and explain the effect of the procedure mystery-3, defined below, which takes any string as its argument.

(define mystery-3
  (lambda (str)
    ((tail-fold-natural null (lambda (new so-far)
                               (cons (string-ref str (- new 1))
                                     so-far)))
     (string-length str))))

Exercise 8

Give an example of a binary procedure proc for which ((fold-natural 0 proc) 5) and ((tail-fold-natural 0 proc) 5) have different values.


This document is available on the World Wide Web as

http://www.cs.grinnell.edu/~stone/courses/scheme/labs/folding.xhtml

created created March 14, 2000
last revised August 24, 2001

John David Stone (stone@cs.grinnell.edu) and Ben Gum (gum@cs.grinnell.edu)