Simply-Scheme-Exercises icon indicating copy to clipboard operation
Simply-Scheme-Exercises copied to clipboard

There should be a vector deepcopy function in 23.15

Open lanjiann opened this issue 10 years ago • 1 comments

Hi buntine, I think there should be a vector deepcopy function in the solution of 23.15. Your solution has a bug that some components reference to the same vector, and they are NOT independent! Try the code below and you'll see the bug:

> (define a (make-array '(2 2 2)))
> a
'#(#(#(0 0) #(0 0)) #(#(0 0) #(0 0)))
> (array-set! a '(1 1 1) 'HERE)
> a
'#(#(#(0 HERE) #(0 HERE)) #(#(0 HERE) #(0 HERE)))
> 

Here is my code:

;; 23.15
(define (make-array dimesions)
  (let ([reverse-dimesions (reverse dimesions)])
    (define (make-array-helper r-dims a-vector)
      (cond [(null? r-dims)
             a-vector]
            [else
             (make-array-helper (cdr r-dims)
                                (n-vector-deepcopy a-vector (car r-dims)))]))    
    (make-array-helper (cdr reverse-dimesions)
                       (make-vector (car reverse-dimesions)))))


(define (n-vector-deepcopy obj n)
  (vector-map (lambda (e) (vector-deepcopy obj)) (make-vector n)))


(define (vector-deepcopy obj)
  (if (vector? obj)
      (vector-map vector-deepcopy obj)
      obj))

;=============================================
; vector-map in exercise 23.5
(define (vector-map a_function a_vector)
  (define (vector-map-helper new_vector index )
     (if (< index 0)
         new_vector
         (begin (vector-set! new_vector index
                             (a_function (vector-ref a_vector index)))
                (vector-map-helper new_vector (- index 1)))))                                   
  (let ((len (vector-length a_vector)))
    (vector-map-helper (make-vector len) (- len 1))))
;==============================================

lanjiann avatar Aug 25 '15 17:08 lanjiann

Ok, great. Feel free to fork the repo, add your fix and then open a pull request. Thanks!

buntine avatar Aug 26 '15 01:08 buntine