I have a tail-recursive function which converts a vector into a list. I understand each line individually, but have a couple questions:
Firstly, in the code what does the code cons ((vector-ref v i) r) (- i 1)
mean? (Marked "Q1".) I know that it takes the i
'th element of vector v
and concatenates it with i-1
, but why have to be i-1
? Why not work with i+1
? e.g. if the vector v length is total 5, then element number 5 is concatenated with the number 4. I understand that it is making the vector list, but why work with i-1
(reducing)? Can anyone give me an explanation?
(define vector->list:rec
(lambda (v)
(letrec ((helper
(lambda (vec r i)
(if (< i 0)
r
(helper vec (cons (vector-ref v i) r) (- i 1)) ;; Q1
))))
(if (> (vector-length v) 0) ;; line 9
(helper v (cons (vector-ref v (- (vector-length v) 1)) '()) (- (vector-length v) 2))
'()))))