سؤال

I have 1 big list of smaller 3-element-lists that look like:

( ("001" "Bob" 80) ("002" "Sam" 85) ("003" "Aaron" 94) etc . . .)

I'm trying to create something like:

No.1: ID=001, Name=’’Bob’’, Grade=80
No.2: ID=002, Name=’’Sam’’, Grade=85
No.3: ID=003, Name=’’Aaron’’, Grade=94

I only have access to display and for-each (no "for" or "printf" functions)

I've been trying to create a for-each function that takes the list and:

pseudo-code:

for-each list in list
display "ID=(car list)"
display "Name ="(cadr list)" "
etc

Any help would be greatly appreciated!

هل كانت مفيدة؟

المحلول

So, your interpreter doesn't have printf after all? that's a shame. We can get the desired output by hand, it's a bit cumbersome but this should work on most Scheme interpreters, notice that an extra procedure is required for keeping track of the index:

(define lst
  '(("001" "Bob" 80) ("002" "Sam" 85) ("003" "Aaron" 94)))

(define (add-index lst)
  (let loop ((lst lst) (idx 1))
    (if (null? lst)
        '()
        (cons (cons idx (car lst))
              (loop (cdr lst) (+ idx 1))))))

(for-each (lambda (e)
            (display "No.")
            (display (car e))
            (display ": ID=")
            (display (cadr e))
            (display ", Name=’’")
            (display (caddr e))
            (display "’’, Grade=")
            (display (cadddr e))
            (newline))
          (add-index lst))

It prints the desired result:

No.1: ID=001, Name=’’Bob’’, Grade=80
No.2: ID=002, Name=’’Sam’’, Grade=85
No.3: ID=003, Name=’’Aaron’’, Grade=94

نصائح أخرى

Here's another version. It avoids construction of a temporary list.

(define lst
  '(("001" "Bob" 80) ("002" "Sam" 85) ("003" "Aaron" 94)))

(define (print-list lst)

  (define (display-one-item item index)
    (display "No.")
    (display index)
    (display ": ID=")
    (display (car item))
    (display ", Name=’’")
    (display (cadr item))
    (display "’’, Grade=")
    (display (caddr item))
    (newline))

  (define (helper in index)
     (if (not (null? in))
        (begin
          (display-one-item (car in) index)
          (helper (cdr in) (+ index 1))
        )))
  (helper lst 0))

  (print-list lst)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top