1

我有一个函数,它接受一个数字,比如 36,然后把它倒过来说

'(6 3)

有没有办法把 6 3 组合成一个数字?

这是我编写的代码。

    (定义(数字-> rdigits 数字)
      (如果 (rdigits (/ (- num (mod num 10)) 10)))))


    (定义可逆?
      (λ (n)
        (条件
          [(空?n)#f]
          [else (odd? (+ n (list (number->rdigits n))))])))

谢谢!

4

1 回答 1

0

您可以使用迭代函数来执行此操作,该函数依次获取列表的每个元素,并累积一个结果。例如:

(define (make-number lst)
  (define (make a lst)
     (if (null? lst)
         a
         (make (+ (* 10 a) (car lst)) (cdr lst))))
  (make 0 lst))

(display (make-number '(6 3)))

make函数使用累加器a和 in 的其余数字lst一步一步地建立最终结果:

a = 0
a = 0*10 + 6 = 6
a = 6*10 + 3 = 63

如果您的列表中有更多数字,这将继续:

a = 63*10 + 5 = 635
a = 635*10 + 9 = 6359

A less efficient implementation that uses a single function could be as follows:

(define (make-number lst)
  (if (null? lst)
      0
      (+ (* (expt 10 (length (cdr lst))) (car lst)) (make-number (cdr lst)))))

This function needs to calculate the length of the remainder of the list for each iteration, as well as calling the expt function 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.

于 2012-10-09T04:38:56.953 回答