Racket - output content of a list

12,298

Solution 1

You can use a for loop. Example:

(for ([x (list 1 2 3)])
    (printf "~s -> ~s\n" x (* x x)))

There are more functional ways to do this, of course, but this way works too. You'll probably want to look at a textbook like How To Design Programs to do the recursive approach. See: http://www.ccs.neu.edu/home/matthias/HtDP2e/

Solution 2

Edit as per comments: Use for-each

(for-each display myList)

Try this:

(void (map display myList))

Breaking it down:

  • (void x) causes x to be ignored instead of returned to the REPL/parent expression as a value.
  • (map function lst): For a list '(a1 a2 ... an) returns the list '((function a1) (function a2) ... (function an)).

So we use map to display all the items, but since we only care about the side-effect and not the return value, we call void on the returned list.

Official docs:

Solution 3

I think the solution that is the easiest to understand it to come up with a so called "list-eater" function. This is the way my university introduced recursion and lists in Racket. Also most books on Racket (i.e. "How To Design Programs" or "Realm Of Racket") explain it this way. This is the code:

(define my-list (list 'data1 'data2 'data3 'data4)) 

(define (print-list a-list-of-data)
  (when (not (empty? a-list-of-data))
    (print (first a-list-of-data))
    (print-list (rest a-list-of-data))))

If you call the function with the example list my-list, you will get the following output:

(print-list my-list)

'data1'data2'data3'data4

The function does the following: As long as the given list is not empty, it grabs the first element of that list and passes it to the function print. Then, it tells itself to do the exact same thing with the rest of the list. (It calls itself on the rest of the list.) This second part is what they call recursion.

However, you can shorten that by using a function called map:

(define (print-list a-list-of-data)
  (map print a-list-of-data))

This basically says that you want the function print to be called on each element of the given list. The output is exactly the same.

Hope it helped!

Share:
12,298
wowpatrick
Author by

wowpatrick

Freelance PHP dev based in Germany.

Updated on June 04, 2022

Comments

  • wowpatrick
    wowpatrick 6 months

    I have defined a list (in Racket/Scheme):

    (define myList (cons 'data1 (cons 'data2 (cons 'data3 (cons 'data4 empty)))))
    

    or

    (list 'data1 'data2 'data3 'data4)
    

    And I want to write a function that cycles through the list and outputs all values of the list.

    (define (outputListData list)
      (cond 
        [(null? list) list]
        [else (getListData)]))
    

    With what function can I cycle through the content of the list? I know one can use first & rest to get list data, but I guess that's not the right way here.

    BTW: Is there a good, compact racket reference like php.net? I find the official Racket docs very confusing ...