chickadee » sparse-vectors » sparse-vector-fold

sparse-vector-fold SPARSE-VECTOR FUNC SEED #!optional SKIP?procedure

When SKIP? is #t unbound elements are skipped, otherwise the FUNC is treated to all elements; an implementation detail.

FUNC ; (INDEX ACC VALUE -> T') ; element function.
T' ; defined-type ; type-of the SEED & ACC.
INDEX ; uinteger ; integer in [0 ...).
VALUE ; * ; but not DEFAULT.
SEED ; T' ; initial value.
ACC ; T' ; accumulated value.
SKIP? ; boolean ; skip unbound? default is #t.

An O(n) operation, where n is total-count.

  • Example:
(define (sparse-vector-reduce sv func seed)
  (sparse-vector-fold sv (lambda (i a v) (func a v)) seed) )

(define (sparse-vector-sum sv) (sparse-vector-reduce sv + 0))

(define (sparse-vector-folded-count sv)
  (sparse-vector-fold sv (lambda (i a v) (add1 a)) 0) )
  • Example, using a SKIP? of #f:
(define (sparse-vector-unoccupied-count sv)
  (sparse-vector-fold sv (lambda (i a v) (if (not v) (add1 a) a)) 0 #f) )