2. Modify the function below to print out the value of x, fibonacci(x-1) and fib
ID: 3870325 • Letter: 2
Question
2. Modify the function below to print out the value of x, fibonacci(x-1) and fibonacci(x-2) in every iteration of the function call:
fun fibonacci (x:int) =
if (x = 0 orelse x = 1)
then x
else fibonacci(x-1) + fibonacci(x-2)
The expression
fibonacci 5;
would produce the output:
x = 1
x = 0
x = 2 f(x-1) = 1 f(x-2) = 0
x = 1
x = 3 f(x-1) = 1 f(x-2) = 1
x = 1
x = 0
x = 2 f(x-1) = 1 f(x-2) = 0
x = 4 f(x-1) = 2 f(x-2) = 1
x = 1
x = 0
x = 2 f(x-1) = 1 f(x-2) = 0
x = 1
x = 3 f(x-1) = 1 f(x-2) = 1
x = 5 f(x-1) = 3 f(x-2) = 2
val it = 5 : int
Explanation / Answer
fun fibonacci (x:int) =
print("x = " + x)
if (x = 0 orelse x = 1)
then
return x
else
a = fibonacci(x-1)
print("f(x-1)="+ a)
b = fibonacci(x-2)
print("f(x-2)="+ b)
return a+b
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.