1

The goal is to create a code that will compute the sum of all integers from a to b and if a > b then it should evaluate to 0.

(define (sum-from-to a b)
  (if (> a b)
      0
      (+ a (sum-from-to (- a 1) b))))

My problem is that when I run this, I run out of memory. What's wrong with my code?

seaweed
  • 21
  • 2

2 Answers2

2

The recursive step is incorrect. Assuming that a <= b the fix is as simple as this:

(define (sum-from-to a b)
  (if (> a b)
      0
      (+ a (sum-from-to (+ a 1) b)))) ; add 1, don't subtract

Think about it, we want a to become closer to b at each step, until it jumps over it. If we decrease a, then it'll move away from b, the exact opposite of what we want. That's why your procedure runs out of memory, a never reached b.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
2

Well, here's one answer a mathematician would give: the sum of all integers from a to b is half of the sum of integers from a to b plus the sum of all integers from b to a. And this is a + b + a + 1 + b - 1 + ... + b + a which is a + b + a + b + ... + a + b. And this in turn is (a + b) * (b - a + 1). So the final sum is (a + b) * (a - b + 1) / 2 therefore. So just write that in Lisp, with the additional condition specified that for b < a:

(define (sum-a-b a b)
  (if (> a b)
      0
      (/ (* (+ a b) (+ (- b a) 1)) 2)))

Of course, what is probably being looked for is either a recursive or an iterative answer. Either of those is a terrible solution to the problem: the recursive answer is terrible in both time & space complexity while the iterative one is merely terrible in terms of time complexity.

People who teach Lisp should stop actively trying to teach people to program badly.

  • 2
    > *People who teach Lisp should stop actively trying to teach people to program badly.* I don't see an applause button, so upvote will have to do. – Kaz Feb 25 '19 at 16:32
  • @Kaz Thanks. It would be interesting to count the number of obvious-students asking for solutions to problems where there's a well-known closed-form. It's reasonable, I suppose, that students don't know enough maths to know it, but their teachers should. It's not like there aren't plenty of algorithms where there *isn't* a closed form. –  Feb 26 '19 at 09:33
  • 1
    There seems to be a problem of Lisp teachers not just teaching people how to program badly, but specifically teaching lousy Lisp that leaves a bad impression of the language family on students. – Kaz Feb 26 '19 at 16:53
  • @Kaz: I think the argument is this is how we keep the language a secret known only by gurus. Or they just can't program. –  Feb 26 '19 at 19:22