So I want to write a Fibonacci function in scala that outputs a tree like so:
fib(3)
| fib(2)
| | fib(1)
| | = 1
| | fib(0)
| | = 0
| = 1
| fib(1)
| = 1
= 2
and my current code is as follows:
var depth: Int = 0
def depthFibonacci(n:Int, depth: Int): Int={
def fibonnaciTailRec(t: Int,i: Int, j: Int): Int = {
println(("| " * depth) + "fib(" + t + ")")
if (t==0) {
println(("| " * depth) + "=" + j)
return j
}
else if (t==1) {
println (("| " * depth) + "=" + i)
return i
}
else {
depthFibonacci(t-1,depth+1) + depthFibonacci(t-2,depth+1)
}
}
fibonnaciTailRec(n,1,0)
}
println(depthFibonacci(3,depth))
which, when run, looks like:
fib(3)
| fib(2)
| | fib(1)
| | =1
| | fib(0)
| | =0
| fib(1)
| =1
2
As you can see there is no "= " at the end of any fibonacci numbers greater than 1, and I am unable to implement this in my depthFibonacci function or else the type becomes Unit. How can I fix this?