Implementing vector-for-each in PLT

François asked how one might implement vector-for-each. Here are two solutions that were provided:
Matthias

#lang scheme
(define-syntax for-each-vector
  (syntax-rules ()
    ((for-each-vector proc vec ...)
     (let ((len (min (vector-length vec) ...)))
       (do ((index 0 (+ index 1)))
         ((= index len))
         (proc (vector-ref vec index) ...))))))
(for-each-vector
 (lambda (a b) (display (+ a b)))
 #( 1 2 3)  #( 1 2 3))
(newline)
;; functional, preferred
;; for-each-vector2
;; (All (A C ...) ((C ... -> A) (Vectorof C) ... -> A))
(define (for-each-vector2 p . vec)
  (for ((i (in-range (apply min (map vector-length vec)))))
    (apply p (map (lambda (v) (vector-ref v i)) vec))))
(for-each-vector2
 (lambda (a b) (display (+ a b)))
 #( 1 2 3)  #( 1 2 3))
(newline)

Sam TH

#lang scheme
(require srfi/43)
(for ([a #(1 2 3)] [b #(1 2 3)])
  (display (+ a b)))
(newline)
(vector-for-each
 (lambda (i a b) (display (+ a b)))
 #(1 2 3) #(1 2 3))

2 thoughts on “Implementing vector-for-each in PLT”

  1. And a stock standard R6RS one:
    (define (vector-for-each p vec1 . vecs)
    (let ((len (vector-length vec1)))
    (do ((i 0 (fx+ i 1)))
    ((fx=? i len))
    (if (null? vecs)
    (p (vector-ref vec1 i))
    (apply p (map (lambda (x) (vector-ref x i))
    (cons vec1 vecs)))))))

Leave a Reply

Your email address will not be published. Required fields are marked *