编写类似阶乘的函数(Prolog) [英] Writing a factorial-like function (Prolog)
问题描述
我必须编写一个Prolog程序来进行计算:
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.
我需要制作一个迭代版本以及一个递归版本.我能够用SML编写该递归版本:
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)
但是由于我是该语言的新手,所以在将其转移到Prolog时遇到了麻烦.另外,我从来没有想过如何做一个迭代的方法.任何帮助将不胜感激!
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!
这是我尝试的Prolog递归版本.它无法编译,甚至可能不正确:
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).
推荐答案
好的,这是正确的代码:)您最大的错误是使变量NewF,NewF2,NewF3依赖于尚无价值的东西(例如:NewF是3 * F ...我们还不知道F).检查下面的代码并注意区别.`
Ok here is the correct code:) Your biggest mistake is making variables NewF,NewF2,NewF3 dependent on something that doesn't have value yet (example: NewF is 3*F... we don't know F yet). Check the code below and notice the difference.`
my_fun(0, 2).
my_fun(1, 0).
my_fun(2, 3).
my_fun(X, F) :- X>=3, NewX is X-3, my_fun(NewX,NewF),
NewX2 is X-2, my_fun(NewX2, NewF2),
NewX3 is X-1, my_fun(NewX3,NewF3),
F is 3*NewF+2*NewF2-NewF3.
以下是使用迭代方法的代码.我们使用累加器存储所需的值,然后使用这些值来获取结果.
Here is the code when using iterative approach. We use accumulators to store the values we need and then use those values to get the result.
my_fun_iterative(0,2) :- !.
my_fun_iterative(1,0) :- !.
my_fun_iterative(2,3) :- !.
my_fun_iterative(X,F) :- X > 2,
my_fun_iterative(0,ZeroV),
my_fun_iterative(1,OneV),
my_fun_iterative(2,TwoV),
V is 3*ZeroV+2*OneV-TwoV,
my_fun_iterative(X,3,OneV,TwoV,V,F),!.
my_fun_iterative(X,X,_,_,F,False) :- not(F=False),!,false.
my_fun_iterative(X,X,_,_,F,F).
my_fun_iterative(X,N,SecondV,ThirdV,Acc,F) :- X > 3,
AccNew is 3*SecondV+2*ThirdV-Acc,
NNew is N+1,
my_fun_iterative(X,NNew,ThirdV,Acc,AccNew,F).
这篇关于编写类似阶乘的函数(Prolog)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!