简体   繁体   English

在Scheme中将递归函数转换为尾递归函数

[英]Converting a recursive function to a tail recursive function in Scheme

I have a function: 我有一个功能:

;; Converting list of integers to a bit string
(define (convert-integers-to-bits integer-representation-of-bits)
  (if (null? integer-representation-of-bits)
    '#*
    (bit-string-append 
      (convert-integers-to-bits (cdr integer-representation-of-bits))
      (unsigned-integer->bit-string 1 (car integer-representation-of-bits)))))

When I run it on small lists, it works, but on real files, it gives me the warning: 当我在小列表上运行它时,它可以工作,但在真实文件上,它会给我警告:

;Aborting!: maximum recursion depth exceeded

Sample usage: 样品用法:

]=> (convert-integers-to-bits '(1 1 0 1 0 1))
;Value: #*110101

Is converting it to a tail recursive function the solution here? 是将它转换为尾递归函数的解决方案吗? If so, any ideas would be appreciated. 如果是这样,任何想法将不胜感激。 Thank you. 谢谢。

A friend of mine solved it, pasted for any future queries: 我的一个朋友解决了它,粘贴以备将来查询:

(define (convert-integers-to-bits integer-representation-of-bits)
   (define (accum rest so-far)
     (if (null? rest)
       (bit-string-append so-far '#*)
       (accum   
         (cdr rest)      
         (bit-string-append     
           (unsigned-integer->bit-string 1 (car rest))
           so-far))))                               
    (accum integer-representation-of-bits '#*))

Yes, converting it into tail recursion will fix the problem. 是的,将其转换为尾递归将解决问题。 The best way to do this in this case is to use an accumulator . 在这种情况下,最好的方法是使用累加器 This is a value that you pass along representing the computation you've already done, or what you have left to do. 这是您传递的值,表示您已经完成的计算,或者您还剩下什么。 For example, you could pass along the bit strings you've produced so far, and then do the append when you get to the end. 例如,您可以传递到目前为止生成的位串,然后在结束时执行append

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM