Reputation: 85
I am trying to convert a math function into prolog, but I keep getting error. Can anyone give me a hint that where is my mistake, please?
I want to convert f (x) = x ˆ 2 + f (x - 1). So I am assuming that this is a recursive procedure. Here is What I have done so far.
function(0,0) :- !.
function(1,1) :- !.
function(X,Y) :-
X1 is ((X * X) + (X - 1)),
function(X1, Y).
I have also tried
function(0,0) :- !.
function(1,1) :- !.
function(X,Y) :-
X1 is (X * X), X2 is (X - 1),
function(X1, N1),
function(X2, N2),
Y is N1 + N2.
Any help is appreciated.
Upvotes: 3
Views: 108
Reputation: 1362
Prolog works using predicate calculus. A predicate can evaluate to true or false.
You need to write what is true (anything else is assumed false as prolog interpreters will use a closed world assumption).
for your function we can define a predicate:
func(X, Y)
where func is a predicate that evaluates to true if X is x and Y is f(X) You need to tell prolog when func(X, Y) is true
func(0, 0).
func(X, Y) :- X > 0, U is X - 1, func(U, V), Y is X * X + V.
The above code can be thought of saying your predicate func is true when X is 0 and Y is 0
This will be your base case. (You only need one since you only have 1 recursive call).
Next is your recursive case:
When is func true for a general X
Upvotes: 3
Reputation: 74227
Try this:
f(0,0) . % f(0) is 0.
f(X,Y) :- % otherwise...
integer(X) , % - constrain X to be an integer, and
X > 0 , % - constrain X to be positive,
X1 is X-1 , # - then decrement X
f(X1,Y1) , % - compute f(X-1) ,
Y is X*X + Y1 % - and add X*X to that to get the result.
. % Easy!
Upvotes: 2