Problem: Spam-Egg List

So on Stoto’s Weblog Tuesday there was a little programming challenge called the Spam-Egg List Problem.

Here is the problem:
Write a function called dumpList that takes as its parameters a string and a reference to an arbitrarily complex nested list and prints the value of each list element on a separate line. The value on each line should be preceded by the string and numbers indicating the depth and index of the element in the list. Assume that the list contains only strings and other nested lists.

For example, given the following nested list:
list = [ 'a string', [ 'a', 'b', 'c' ], ’spam’, [ 'eggs' ] ] and the string ‘Foo’, the output of dumpList(’Foo’, list) would look like:

Foo.0: a string
Foo.1.0: a
Foo.1.1: b
Foo.1.2: c
Foo.2: spam
Foo.3.0: eggs

My solution (in scheme) is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
(define (dump-list word sequence)
 
  (define (dump-list-iter word sequence count)
 
    (if (null? sequence)
 
        '()
 
        (cond ((list? (car sequence))
 
                (dump-list-iter
 
                 (string-append
 
                  word "." (number->string count)) (car sequence) 0)
 
                (dump-list-iter word (cdr sequence) (+ count 1)))
 
               (#t
 
                (display
 
                 (string-append word "." (number->string count)
 
                                ": " (car sequence)))
 
                (newline)
 
                (dump-list-iter word (cdr sequence) (+ count 1))))))
 
  (dump-list-iter word sequence 0))

It’s a simple recursive solution with side-effects (printing). It would be relatively easy to rework it to maintain a list of strings and print them at the very end, but the problem didn’t call for it, so I’m satisfied with this solution.


About this entry