Search code examples
schemelispracketsicp

Is there a way to use for-each function in vectors as it is used in Lists in Scheme


In scheme when working with Lists, one can easily use for-each. I have used it in the following code.

(for-each (lambda (arg)
          (diplayln arg)

and the output is

1

2

3

4

I want to use the same analogy for vectors, am implementing a function vector-for-each

such that (vector-for-each display (vector "red" "orange")). The output should be "red" "orange".

What is the best way of implementing for-each for vectors in scheme?


Solution

  • This will do the trick in Racket:

    (for ([color (vector "red" "orange")])
      (display (string-append "\"" color "\"")) ; or use `displayln`
      (newline))
    

    I'd rather use printf, but if you want to use display it's fine. This is how I'd do it:

    (for ([color (vector "red" "orange")])
      (printf "~s~n" color))