[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: peasant revolt against DrScheme!



Michael Vanier <mvanier@bbb.caltech.edu> writes:

> Let's say I agree 100% with everything you've said so far.
> Recursive functions are extremely effective for dealing with many
> data structures, lists among them.  What if you want to iterate down
> a vector and pick out the largest element?  You can certainly do it
> recursively:
> 
> (let loop ((v #(1 10 3 22 4))
>            (i 0) ; index
>            (max -1)) ; assume all elements of v are positive
>     (if (>= i (vector-length v))
>         (begin (display "maximum = ") (display max) (newline))
>         (let ((v_i (vector-ref v i)))
>           (if (> v_i max)
>               (loop v (+ i 1) v_i)
> 			  (loop v (+ i 1) max)))))
> 
> But this seems rather excessive compared to a straight iteration
> construct (and no mutation is going on either).  Vectors are very
> important data structures in (for instance) numeric programming, so
> this issue is not trivial.

How about:

(define (vector-fold kons knil vec)
  (let next ((i (- (vector-length vec) 1))
	     (rest knil))
    (if (< i 0)
	rest
	(next (- i 1) (kons (vector-ref vec i) rest)))))

(define (vector-max vec)
  (or (vector-fold (lambda (a b)
		     (if b (max a b) a))
		   #f vec)
      (error "Empty vector")))

Separate out traversing the data structure from what you're doing with
elements in the data structure and this is what you get.  You could
express your version even more succinctly:

(define (vector-max vec) (vector-fold max -1 vec))

-- 
         Mark Seaborn
   - mseaborn@bigfoot.com - http://www.srcf.ucam.org/~mrs35/ -

                  How to write good:
          ``7. It is wrong to ever split an infinitive.''