Reputation: 105
So, I know that there is a solution using the if statement which is the following
(defun numdigits (n)
(if (< -10 n 10)
1
(1+ (numdigits (truncate n 10)))))
But I'm trying to deepen my knowledge and to understand to go for transforming if statements to the cond statement. SO I tried it out using the cond statement, but I receive an error, and quite honestly, I don't know why.
Here's what I did:
(defun nbDigits (digit)
(cond
((> 0 (- digit 10)) 1)
(t (1 + (nbDigits (truncate digit 10))))
)
)
The logic I'm having is: If 0 is greater than x-10, return 1 ( as this means the number is smaller than 10). Else, return 1 + nbDigits(the quotient of the digit when it's divided by 10), which should go until it reaches the base case.
I'm getting the error: Illegal argument in functor position: 1 in (1 + (NBDIGITS (TRUNCATE DIGIT 10))). But I don't understand how to go about this error.. Did I do a wrong call? Thanks.
Upvotes: 0
Views: 1278
Reputation: 1934
A simple space between 1
and +
is changing the function 1+
into two elements. Remove that space and you are done.
Incidentally, simplify your math by writing (< digit 10)
instead of (> 0 (- digit 10))
In the end it should look like this:
(defun nbDigits (digit)
(cond
((< digit 10) 1)
(t (1+ (nbDigits (truncate digit 10))))
)
)
Upvotes: 3