Schematic: Changing recursion to tail recursion

I'm not sure how to turn count-forward into a tail recursive program. It takes a non-negative number, nand returns a list of integers from 0to n(including n).

Edit: Well, I finally got this to work. The problem was not that my current program was recursive, and I needed to make it tail recursive. It was simply wrong. The actual answer is really short and clean. Therefore, if someone else is stuck with this, and is also a complete noob programming, here are some tips that might help:

1) Your helper program is designed to keep track of the list so far.

2) Its basic case ... If x = 0, what are you doing? add 0 to .. something.

3) Repeat on x - 1 and then add x to your list so far.

4) When you get to your actual program, think-ahead, all you need is an assistant. But remember that this requires two arguments!

+3
source share
1 answer

The only recursive function here is renaming the list. It is tail recursive, because the call itself is the last operation in the function body.

Your function to generate a non-decreasing sequence from zero to mthat contains the sequential results of adding 1to the previous element will look something like this:

(define (my-reverse lst)
  (define (rev-do xs ys)
    (if (empty? xs)
        ys
        (rev-do (cdr xs) (cons (car xs) ys))))
  (rev-do lst empty))

(define (seq m n)
  (seq-do m n (list m)))

(define (seq-do m n xs)
  (if (= m n)
      (my-reverse xs)
      (let ((next (add1 m)))
        (seq-do next n (cons next xs)))))

(define (seq-from-zero m)
  (seq 0 m))

Test:

> (seq-from-zero 10)
(0 1 2 3 4 5 6 7 8 9 10)

seq-do - m n; , - .

reverse , .

+5

Source: https://habr.com/ru/post/1793734/


All Articles