I've been working on the examples from SICP, and I've run into some trouble writing the two versions of accumulate in example 1.32. So far, my code looks like this.
Recursive version:
#lang racket
(provide accumulate)
(define (accumulate f a next b comb null)
(if(> a b)
null
(comb (f a)
(accumulate f (next a) next b comb null))))
Iterative version:
#lang racket
(provide accumulate)
(define (accumulate f a next b comb null)
(define (iter cur_a result)
(if (> cur_a b)
result
(iter (next cur_a) (comb (f cur_a) result))))
(iter a null))
While these two functions give the same result for simple comb
terms like addition and multiplication, something like `(lambda (x y) (+ (* 3 x) (* 3 y))) will cause the two functions to give different results, due to the direction of application. The recursive version goes left from the right end of the range, while the iterative version goes right from the left end of the range.
I'm wondering if it's possible to change this direction for the functions, so that one could choose whether the code would run left or right. It seems to me that to do so, one would have to give a prev
term instead of a next
term so that the function could run the other way. Is there any other way to implement this without touching the function parameters?