user2976636
user2976636

Reputation: 105

Define a recursive function to count the numbers of digits in a number in common lisp

This is what I did until now it tells me that it is not of type list.

(defun number_list(n)
  (setf x 
        (if (zerop (truncate n 10)) 
          (list n)
          (append (number_list (truncate n 10)) (list (mod n 10)))))
  (length x))

When I remove the (length x) I can see that the result is a list however.

Would appreciate any help.

Upvotes: 2

Views: 2098

Answers (2)

Rainer Joswig
Rainer Joswig

Reputation: 139251

If you want to get the decimal digits and then count the length, assuming that numbers are 0 or greater integers.

(defun number-list (n) 
  (if (< n 10) 
      (list n)
    (cons (mod n 10)
          (number-list (truncate n 10)))))

CL-USER 44 > (length (number-list 123456789))
9

But it is preferable to directly count the digits. See the other answers.

Upvotes: 1

uselpa
uselpa

Reputation: 18917

Your solution uses a global variable x, which is generally a bad idea, especially in recursive functions. Then, you create a list in order to count the number of digits. This is not really necessary.

Using a list

If you want to work with a list, I suggest you split the problem in 2 parts:

1. convert a number to a list

Your function works well for this if you remove setf x:

(defun number_list(n)
  (if (zerop (truncate n 10)) 
    (list n)
    (append (number_list (truncate n 10)) (list (mod n 10)))))

2. count the number of digits

(defun numdigits (n)
  (length (number_list n))).

Alternative

But I would suggest a simple recursive definition such as:

(defun numdigits (n)
  (if (< -10 n 10)
    1
    (1+ (numdigits (truncate n 10)))))

Upvotes: 3

Related Questions