您可以使用迭代函数来执行此操作,该函数依次获取列表的每个元素,并累积一个结果。例如:
(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.