I have to write a Prolog program to compute:
f(0) = 2, f(1) = 0, f(2) = 3, f(n) = 3f(n-3) + 2f(n-2) - f(n-1) for n≥3.
I need to make an iterative version, as well as a recursive version. I was able to write that recursive version in SML:
fun myFunc 0 = 2 | myFunc 1 = 0 | myFunc 2 = 3 | myFunc x = 3* myFunc(x-3) + 2* myFunc(x-2) - myFunc(x-1) But am having trouble transferring it to Prolog as i'm very new to the language. Also, I was never able to figure out how to do an iterative approach. Any help would be greatly appreciated!
Here is my attempt at the Prolog recursive version. It doesn't compile and probably isn't even close to right:
my_Fun(0, 2). my_Fun(1, 0). my_Fun(2, 3). my_Fun(X, F) :- X>=3, NewX is X-3, NewF is 3 * F, my_fun(NewX,NewF), NewX2 is X-2, NewF2 is 2 * F, my_fun(NewX2, NewF2), NewX3 is X-1, NewF3 is F, myFun(NewX3,NewF3).
f(n)depends on three previous values off, so just maintain them:step (n,a,b,c) = (n+1,b,c,3a+2b-c).