I have a function that takes a number such as 36, and reverses it to say
'(6 3)
Is there anyway to combine that 6 3 to make it one number?
Here is the code that I have written.
(define (number->rdigits num)
(if (rdigits (/ (- num (mod num 10)) 10)))))
(define reversible?
(lambda (n)
(cond
[(null? n) #f]
[else (odd? (+ n (list (number->rdigits n))))])))
Thanks!
You can do this using an iterative function that takes each element of the list in turn, accumulating a result. For example:
The
makefunction uses an accumulatoraand the rest of the digits inlstto build up the final result one step at a time:If you had more digits in your list, this would continue:
A less efficient implementation that uses a single function could be as follows:
This function needs to calculate the
lengthof the remainder of the list for each iteration, as well as calling theexptfunction repeatedly. Also, this implementation is not properly tail recursive so it builds up multiple stack frames during execution before unwinding them all after it reaches its maximum recursion depth.