简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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