2

I am making a tribonacci function that, given n, returns the value, with n(0)=0,n(1)=0,n(2)=1.
My current code is just normal recursion, but how can i make it tail recursive?

(define (tribonacci n)
 (if ( < n 0) #f
  (cond ((= n 0) 0)
        ((= n 1) 0)
        ((= n 2) 1)
        ((> n 0)
          (+ (tribonacci (- n 1)) (+ (tribonacci (- n 2))(tribonacci (- n 3)))))))) 
Slava A.
  • 97
  • 6

2 Answers2

3

Any recursive function that uses some of the previous answers to compute the next can be made iterative by keeping the number of variables as the base cases. In the case of plain fibonacci you have two base cases and the next value is always the sum of the two previous

(define (fib n)
  (let loop ((n n) (a 0) (b 1))
    (if (zero? n)
        a
        (loop (- n 1) b (+ a b)))))

So imagine you want (fib 4) it does these iterations:

n a b
4 0 1
3 1 1
2 1 2
1 2 3
0 3 5 

Notice that a actually are all the fibonacci numbers from the beginning while b is all the fibonacci numbers from the second value and we calculate one more than the result we need. Another way to see it is that the variables are like a window that moves over the fibonacci numbers.

I'll leave you to do the same with your special version as it can be solved in the exact same way using a third variable in the iterative loop. Good luck!

Sylwester
  • 47,942
  • 4
  • 47
  • 79
0

Here's a version that uses a tail recursive function.

(define (tribonacci n)
  (define (helper n a b c)
    (format #t "a: ~a, b: ~a, c: ~a\n" a b c)
    (if (= n 0)
      a
      (helper (- n 1) b c (+ a b c))))

  (if ( < n 0) #f
    (helper n 0 0 1)))

Output of executing (tribonacci 10):

a: 0, b: 0, c: 1
a: 0, b: 1, c: 1
a: 1, b: 1, c: 2
a: 1, b: 2, c: 4
a: 2, b: 4, c: 7
a: 4, b: 7, c: 13
a: 7, b: 13, c: 24
a: 13, b: 24, c: 44
a: 24, b: 44, c: 81
a: 44, b: 81, c: 149
a: 81, b: 149, c: 274
R Sahu
  • 204,454
  • 14
  • 159
  • 270