简体   繁体   中英

How to count the digits of a given number in scheme?recursively and iteratively

I know how to calculate the sum of the digits of a number:

(define (sum-of-digits x)  
  (if (= x 0) 0
      (+ (modulo x 10) 
         (sum-of-digits (/ (- x (modulo x 10))
                           10)))))`

But I just don't have a clue to make a count of the digits. And also don't know how to do that by a linear iterative progress.

Thanks!!

You are very close to the answer.

In order to figure out how to change sum-of-digits into count-of-digits, try writing some test cases. A test case must include an example of calling the function, and also the expected result.

As a side note, this is an example of generative recursion , and you shouldn't be tackling it until you've done a bunch of problems like "add the numbers in a list", "count the elements in a list", etc.

Some hints regarding each of your questions:

  1. For counting digits, you don't need to add the current digit (as is the case in your code). Just add 1
  2. There are several strategies for transforming a recursive solution (like yours) to a tail recursion (one that generates a linear iterative progress). Here's a short list:

    • Add an extra parameter to the function to hold the result accumulated so far
    • Pass the initial value for the accumulator the first time you call the procedure, typically this is the same value that you'd have returned at the base case in a "normal" (non-tail-recursive) recursion.
    • Return the accumulator at the base case of the recursion
    • At the recursive step, update the accumulated result with a new value and pass it to the recursive call
    • And the most important: when the time comes to call the recursion, make sure to call it as the last expression with no "additional work" to be performed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM