How to calculate the sum of a digits of a number in Scheme?

10,065

Solution 1

An alternative method would be to loop over the digits by using modulo. I'm not as used to scheme syntax, but here's a function that works in Lisp for non-negative integers (and with a little work could encompass decimals and negative values):

(defun sum-of-digits(x) 
  (if (= x 0) 0 
      (+ (mod x 10) 
         (sum-of-digits (/ (- x (mod x 10)) 10)))))

Solution 2

Something like this can do your digits thing arithmetically rather than string style:

(define (digits n)
    (if (zero? n)
        '()
        (cons (remainder n 10) (digits2 (quotient n 10))))

Anyway, idk if its what you're doing but this question makes me think Project Euler. And if so, you're going to appreciate both of these functions in future problems.

Above is the hard part, this is the rest:

(foldr + (digits 12345) 0)

OR

(apply + (digits 1234))

EDIT - I got rid of intLength above, but in case you still want it.

(define (intLength x)
   (define (intLengthP x c)
      (if (zero? x)
          c
          (intLengthP (quotient x 10) (+ c 1))
      )
   )
   (intLengthP x 0))

Solution 3

Those #\1, #\2 things are characters. I hate to RTFM you, but the Racket docs are really good here. If you highlight string->list in DrRacket and hit F1, you should get a browser window with a bunch of useful information.

So as not to keep you in the dark; I think I'd probably use the "string" function as the missing step in your solution:

(map string (list #\a #\b))

... produces

(list "a" "b")
Share:
10,065
bearzk
Author by

bearzk

Updated on June 04, 2022

Comments

  • bearzk
    bearzk 7 months

    I want to calculate the sum of digits of a number in Scheme. It should work like this:

    >(sum-of-digits 123)
     6
    

    My idea is to transform the number 123 to string "123" and then transform it to a list '(1 2 3) and then use (apply + '(1 2 3)) to get 6.

    but it's unfortunately not working like I imagined.

    >(string->list(number->string 123))
    '(#\1 #\2 #\3)
    

    Apparently '(#\1 #\2 #\3) is not same as '(1 2 3)... because I'm using language racket under DrRacket, so I can not use the function like char->digit.

    Can anyone help me fix this?