I am trying to create a list of digits starting from a list of numbers.
For example I want to break (11 4 6) into (1 5 6) by dividing the head of the list to 10 if the head is >= 10 and adding 1 to the next element.
My code looks like this
(defun createparameters (l)
(cond ((null l) l)
((> 9 (car l)) (setf (car l) (mod (car l ) 10))
(setf (cadr l) (+ (cadr l) 1)))
(t (createparameters (cdr l)))))
but it does not change my referenced list. Help would be greatly appreciated.
You write that you want the operation done if the first element is greater than 9, but in your code you are doing the opposite.
(> 9 (car l))
is the same as infix9 > (car l)
so you do your thing when first element is 8 or lower.Here is a functional version of your code that continues to process the next sublist:
Here is a modified mutating version (similar to your code):
I'm starting to wonder if this is a carry so that the first element is the least significant digit and the last is the most. If so just adding one will only work if the number always are below 20 and the code will not work if the last digit became 10 or higher.
A direct approach
Here's a version that performs the task directly.
A modular approach
A more modular approach might break this down into two parts. First, given a list of digits, each of which might be greater than 9, we can reconstruct the original number as a number (i.e., not as a list of digits). This is pretty straightforward:
Now, converting a number into a list of digits isn't too hard either.
Now, we can observe that
digits->number
converts the digits list into the number in the form that we need, even when there are 'digits' that are greater than 9.number->digits
always produces a representation where all the digits are less than 10. Thus, we can also implementdecompose
asnumber->digits
ofdigits->number
.As an interesting observation, I think you can say that the space of input for
decompose
is lists of non-negative integers, and that each list of non-negative integers less than 10 is a fixed point ofdecompose
.