Blob


1 ;; The first three lines of this file were inserted by DrScheme. They record metadata
2 ;; about the language level of this file in a form that our tools can easily process.
3 #reader(lib "htdp-advanced-reader.ss" "lang")((modname |29.3|) (read-case-sensitive #t) (teachpacks ((lib "draw.ss" "teachpack" "htdp") (lib "arrow.ss" "teachpack" "htdp") (lib "gui.ss" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ((lib "draw.ss" "teachpack" "htdp") (lib "arrow.ss" "teachpack" "htdp") (lib "gui.ss" "teachpack" "htdp")))))
4 ;vector-sum : vector -> number
5 ;Given avector, sum all its entries.
7 (define (vector-sum avector)
8 (local ((define (vector-sum-aux i)
9 (cond
10 [(zero? i) 0]
11 [else (+ (vector-ref avector (sub1 i))
12 (vector-sum-aux (sub1 i)))])))
13 (vector-sum-aux (vector-length avector))))
15 ;vector-sum-aux : vector N -> number
16 ;Given avector and i, sum up the numbers within a vector in [0,i) starting from i-1 to 0.
19 ;vector-sum-lr : vector -> number
20 ;Given avector, sums the vector from left to right (like English-reading humans would do).
22 (define (vector-sum-lr avector)
23 (local ((define avec-length (vector-length avector))
24 (define (vector-sum-lr-aux i)
25 (cond
26 [(= avec-length i) 0]
27 [else (+ (vector-ref avector i)
28 (vector-sum-lr-aux (add1 i)))])))
29 (vector-sum-lr-aux 0)))
31 ;vector-sum-lr-aux : vector N -> number
32 ;Given avector and i, sum up the elements within the vector from [0,i) from left to right.
35 (define vector1 (vector 5 6 7 8))
36 (equal? (vector-sum vector1) 26)
37 (equal? (vector-sum vector1) (vector-sum-lr vector1))