Philip Rego
Philip Rego

Reputation: 648

Scheme Loop Through a List

How would I loop this list in scheme?

(define test-document '(
                    ((h e l l o))
                    ((t h i s)(i s)(t e s t))
                    ))

What I tried it only showed the first column.

Upvotes: 0

Views: 14139

Answers (3)

uselpa
uselpa

Reputation: 18937

Were you thinking of something like this?

(define (walk-list lst)
  (define (sub-walk lst)
    (if (null? lst)
        '()
        (let ((x (car lst)))
          (if (list? x)
              (cons (sub-walk x) (sub-walk (cdr lst)))
              (apply string-append (map symbol->string lst))))))
  (flatten (sub-walk lst)))

then

(walk-list test-document)
=> '("hello" "this" "is" "test")

which you can process using the usual suspects (map, filter, ...).

If your Scheme has no flatten procedure, you can use this one:

(define (flatten lst)
  (reverse
   (let loop ((lst lst) (res null))
     (if (null? lst)
         res
         (let ((c (car lst)))
           (loop (cdr lst) (if (pair? c) (loop c res) (cons c res))))))))

Upvotes: 1

Aadit M Shah
Aadit M Shah

Reputation: 74244

What you have is a list of lists of lists:

(define test-document '(((h e l l o)) ((t h i s) (i s) (t e s t))))

To loop over its elements you must create a loop of a loop of a loop. To do so we can use map and curry as follows:

(map (curry map (curry map
        (compose string->symbol string-upcase symbol->string)))
    test-document)

This produces the following output:

(((H E L L O)) ((T H I S) (I S) (T E S T)))

If your Scheme interpreter doesn't have a built-in curry function then you can define one as follows:

(define (curry func . args)
    (lambda x (apply func (append args x))))

Hope this helped.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206747

car and cdr family of functions are your friends to navigate lists. Here are some examples.

(define test-document '(
                    ((h e l l o))
                    ((t h i s)(i s)(t e s t))
                    ))

(car test-document)  ;; `((h e l l o))
(caar test-document)  ;; `(h e l l o)
(cadr test-document) ;; `((t h i s) (i s) (t e s t))
(car (cadr test-document) ;; `(t h i s)
(cadr (cadr test-document) ;; `(i s)
(caddr (cadr test-document) ;; `(test )

Define a function that will walk the list and call a function for each item that is not a list.

(define (walk-list lst fun)
   (if (not (list? lst))
      (fun lst)
      (if (not (null? lst))
         (begin
            (walk-list (car lst) fun)
            (walk-list (cdr lst) fun)))))

Call it to print each item.

(walk-list test-document print)

Upvotes: 3

Related Questions