2
votes

I'm trying to get the lowest integer out of a vector only containing numbers. I know how to do it with lists. You compare the first two values of the list and depending on which is larger you either save your value to output it later or call the function again with the rest of the list (all elements except the first) using the cdr procedure.

But with vectors I'm completely lost. My guess would be that the way of thinking about the solution would be the same for lists and vectors. I've been reading on the racket-lang website but haven't been able to come up with a solution to the problem. The procedures I've been experimenting most with are vector-ref and vector-length as they seem to be the most useful in this problem (but this is my first time working with vectors so what do I know).

So my two questions are:

  1. How can we get all values except the first from a vector? Is there a procedure like cdr but for vectors?

  2. If you were working with lists you would use cons to save the values you would want to output. But is there a similar way of doing it when working with vectors?

Thanks!

2
See also Vector Programming Using Structural Recursion: An Introduction to Vectors for Beginners, which presents an HtDP-style design recipe for functions on vectors. - Alexis King

2 Answers

3
votes

The simplest solution is to use a variant of for called for/fold. I thought there were an for/min but alas.

#lang racket
(define v (vector 11 12 13  4 15 16))

(for/fold ([m +inf.0]) ([x (in-vector v)])
  (min m x))

If you like a more explicit approach:

(define (vector-min xs)
  (define n (vector-length xs))
  (let loop ([i 0]           ; running index
             [m +inf.0])     ; minimum value so far
    (cond
      [(= i n)               ; if the end is reached
       m]                    ;     return the minimum
      [else                  ; else
       (define x (vector-ref v i)) ; get new element in vector
       (loop (+ i 1)         ;   increment index
             (min m x))])))  ;   new minimum

UPDATE

(let loop ([x 1] [y 10])
   (loop (+ x 1) (- y 1))

is the same as:

(let ()
   (define (loop (x y) 
     (loop (+ x 1) (- y 1)))
   (loop 1 10))
2
votes

Vectors are O(1) access and indexed so it is a completely different data structure, however you have SEFI-43 which is like the SRFI-1 List library, but for vectors.

#lang racket
(require srfi/43)

(define (min-element lst)
  (vector-fold min (vector-ref lst 0) lst))

(max-element #(7 8 1 2 3 4 5 12))
; ==> 1