CS 251: Programming Languages

Fall 2017

hw3: Lazy lists

Due: Friday, 09/22 at 22:00

This assignment is to be done individually. You can share ideas and thoughts with other people in the class, but you should code your own assignment.

1. Goals

To build a data structure to represent a (possibly infinite) sequence of elements.

2. Introduction

Try the following in Python 2
range(3,23)
xrange(3,23)
for n in xrange(3,23):
   print n
and the following in Python 3
range(3,23)
for n in range(3,23):
   print(n)
It would seem that xrange in Python 2 and range in Python 3 yield some kind of (relatively small) objects that represent (possibly large) sequences of numbers. The actual sequence does not need to be generated until needed. Think about difference in storage requirements when the 23 above are replaced with, say, 23000000000000. (If you want to learn more, read about iterators and generators in Python.)

We now try to do this in Scheme. Recall that a non-empty list in Scheme consists of two parts:

Analogously, a non-empty lazy list in Scheme consists of two parts: where the thunk is a zero-parameter function that, when called, returns a lazy list.

The key is that the body of a function in Scheme is not evaluated until the function is called, so infinite recursion does not appear to be a problem.

The Scheme function (range a b) generates a list of integers from a up to and including b, like range(a,b+1) in Python 2.

(define range
  (lambda (a b)
    (if (> a b)
        '()
        (cons a
              (range (+ a 1) b)))))
Compare this with (lazy-range a b), which generates a lazy range, like xrange(a,b+1) in Python 2 or range(a,b+1) in Python 3.
(define lazy-range
  (lambda (a b)
    (if (> a b)
        '()
        (cons a
              (lambda () (lazy-range (+ a 1) b))))))
The result of (lazy-range a b) is a cons cell, whose car is is the first integer; and whose cdr is a zero-parameter function that, when called, returns the rest of the sequence represented as a pair of the same (lazy) structure. We still use the empty list () to represent an empty lazy list.

3. Specification

4. Notes

5. Optional Challenges

6. Submission

Submit your code in a file called lazy-list.scm. We will be grading this using Moodle's anonymous grading capabilities, so make sure that your names are not included in your file.

Start early, have fun, and discuss questions on Moodle.