Reputation: 343
In the following code the values for avg and avg2 change as the code progresses. How can I make it so that the values are constant throughout the function without defining them outside the function? Should I use a helper function?
(define (covariance-list x y)
(let ((avg (average x)))
(let ((avg2 (average y)))
(if (null? x)
'()
(cons (* (- (car x) avg)(- (car y) avg2))
(covariance-list (cdr x) (cdr y)))))))
Upvotes: 0
Views: 84
Reputation: 1902
One way would be with an auxiliary function:
(define (covariance-list x y)
(define (covariance-list-aux x y avg-x avg-y)
(if (null? x)
'()
(cons (* (- (car x) avg-x) (- (car y) avg-y))
(covariance-list-aux (cdr x) (cdr y) avg-x avg-y))))
(covariance-list-aux x y (average x) (average y)))
Upvotes: 1
Reputation: 693
I don't think you want them constant, since they depend on the parameters of the function. You probably just want them to not be recomputed during each recursive call.
(define (covariance-list x y)
(let ((avg (average x))
(avg2 (average y)))
(let loop ((x x)
(y y))
(if (null? x)
'()
(cons (* (- (car x) avg)
(- (car y) avg2))
(loop (cdr x) (cdr y)))))))
Upvotes: 3