Apex Predator
Apex Predator

Reputation: 171

Get the Sum of given number in scheme

Hi i want my function to sum digits such that the result is less than 10 (77 = 14=5). dont know why it's passing the base case

(define (reduct n)
  (if(< n 10) n
     (+(modulo n 10)(reduct (truncate(/ n 10))))))

Upvotes: 0

Views: 45

Answers (1)

C. K. Young
C. K. Young

Reputation: 223023

You forgot to call reduct again after adding. Here's the fixed version:

(define (reduct n)
  (if (< n 10)
      n
      (reduct (+ (modulo n 10) (reduct (quotient n 10))))))

Note that the inner reduct recursion is actually redundant and can be removed, leaving:

(define (reduct n)
  (if (< n 10)
      n
      (reduct (+ (modulo n 10) (quotient n 10)))))

or, if you want to only divide once (and get the modulo too), you can use the R7RS floor/ procedure:

(define (reduct n)
  (if (< n 10)
      n
      (reduct (call-with-values (lambda () (floor/ n 10)) +))))

(This is, by the way, a pure loop. A Ruby version could look like:

def reduct(n)
  n = n % 10 + n / 10 while n >= 10
  n
end

or (for the one-division-only approach)

def reduct(n)
  n = n.divmod(10).reduce(:+) while n >= 10
  n
end

except that it uses mutation unlike the Scheme version.)

However, as my comment already says, the result will always be the same as doing (modulo n 9) (except that 0 should become 9, so (+ (modulo (- n 1) 9) 1) is probably more correct), so if you're doing this for numerological purposes or otherwise not a homework which requires you to do it the "hard way", just use that.

Upvotes: 1

Related Questions