; Side effects! ; - side effects change the value of a predefined (either with define or let) variable ; - we have not done this yet, so up until now, once we have defined something ; it has stayed at that value ; - side effects will allow us to change the value of a variable, and commands that do ; that, we denote with an ! at the end ; always remember to do this when working with vectors (print-vector-length #f) ; today we will focus on: vector-set!, which is a bit similar to vector-ref, except ; that instead of getting the the value in a certain position, it sets the value in a ; certain position ; * note that vector-set! like most side effect commands, returns nothing ; but it modifies the input vector (define vec (vector 0 1 2 3 4)) vec ; should return #(0 1 2 3 4) ;(vector-set! vec 2 'elephant) ;vec ; should return #(0 1 elephant 3 4) ; now I will write double-vector-elements and double-vector-elements! ; this will change the input vector, so that all of its elements are doubled (define double-vector-elements! (lambda (vec) ; typically we will need a kernel which keeps track of the position ; when we work with vectors (let kernel ((pos (- (vector-length vec) 1))) ; for side effects since we do not return anything, I want to check ; if we need to keep going... (if (>= pos 0) ; the begin command allows you to do more than one thing (begin ; this changes position pos (vector-set! vec pos (* 2 (vector-ref vec pos))) ; this changes the rest of the positions (kernel (- pos 1))))))) ; now if I call (double-vector-elements! vec) ; this by itself doesn't return anything vec ; this should return #(0 2 4 6 8) ; now let's write double-vector-elements, which returns a new vector which ; is like the input vector, except the elements are doubled (define double-vector-elements (lambda (vec) ; to return a new vector, I have have to make a new vector, and I will use let to ; do this (let ((double-vec (make-vector (vector-length vec)))) ; now we will use a kernel and procede similarly to the previous procedure ; I prefer starting at the end of vectors, but you can also start at the beginning (let kernel ((pos (- (vector-length vec) 1))) (if (>= pos 0) (begin (vector-set! double-vec pos (* 2 (vector-ref vec pos))) (kernel (- pos 1))) ; this time when I am finished, I want to return double-vec double-vec))))) ; now what does this return (double-vector-elements vec) ; this returns a new vector #(0 4 8 12 16) (since we doubled vec previously)