Creating a vector-filter function without the use of lists as an intermediate value.
Creating a vector-filter function without the use of lists as an intermediate value.
Date Created:Sunday October 26th, 2008 06:06 PM
Date Modified:Sunday October 26th, 2008 06:10 PM
(define (vector-filter pred vec)
(let ((num (vector-filter-count pred vec 0 (- (vector-length vec) 1))))
(vector-fill pred (make-vector num) vec 0 0)
)
)
;; THIS DETERMINES THE NUMBER OF VALUES THAT RETURN TRUE FOR THE PREDICATE
(define (vector-filter-count pred vec count n)
(if (= n -1)
count
(let ((val (vector-ref vec n)))
(if (pred val)
(vector-filter-count pred vec (+ count 1) (- n 1))
(vector-filter-count pred vec count (- n 1))))))
;; THIS PLACES VALUES INTO THE nth POSITION OF THE NEW VECTOR WHEN
;; THE kth POSITION OF THE OLD VECTOR RETURNS TRUE FOR THE PREDICATE
;; THEREFORE, INCREMENT k each time, but not necessarily n
(define (vector-fill pred vec vec-old n k)
(if (= n (vector-length vec))
vec
(if (pred (vector-ref vec-old k))
(begin
(vector-set! vec n (vector-ref vec-old k))
(vector-fill pred vec vec-old (+ n 1) (+ k 1)))
(vector-fill pred vec vec-old n (+ k 1)))))
(define v1 (vector 0 1 2 3 4 5 6 7 8))
(define pred (lambda (x) (= (modulo x 2) 0)))
;; stk> (vector-filter pred v1)
;; stk> #(0 2 4 6 8)
Downloads:
Download: vector-filter.scm 1 KB
Please login or Click Here to register for downloads
Vector Filter by Dan Lynch
is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
Based on a work at www.3daet.com
Permissions beyond the scope of this license may be available at http://www.3daet.com
