I’m trying to write a function which accumulates the value interval with the given operator and adds the initial value. Example:
(accumulate-interval + 0 2 4) :
2 + 3 + 4 + 0 = 9
(accumulate-interval * 1 2 5) :
2 * 3 * 4 * 5 * 1 = 120
Note: Only (+) and (*) to work is enough for me.
My code is:
(define accumulate-interval
(lambda (op init lower upper) (if (= upper lower)
(lambda (x) (op x init))
(lambda (x)
(op
((accumulate-interval op init lower (- upper 1)) x)))) ))
It returns a procedure instead of a value.
I’d really appreciate if you can help.
It returns a function because that is what you are returning. lambda is a function which creates an anonymous function and returns a reference to it. When your code does
It is using lambda to create an anonymous function, return the reference to it and assign that reference as the value of accumulate-interval. accumulate-interval is thus associated with that function and that function is run whenever accumulate-interval is evaluated in the function position in a list.
Now, your accumulate-interval function consists of a single if expression which does
So if upper and lower are equal, it returns a reference to one anonymous function, otherwise it returns a different one. This is what you have told it to do.
I don’t know what you are trying to do, here, but I suspect you just want to execute the code which you are mistakenly wrapping in a function and returning. So I think your code is meant to look more like
Which should work, although I think you need to rethink your arguments because that recursive call is not in tail position.
Thinking about it,
Would work and be tail-recursive.
Note: I don’t normally do people’s homework for them, but I think you may have more than one misconception about Scheme syntax and showing working code was easier than exploring each of those possible misunderstandings separately and in combination.