Zzhh82
Zzhh82

Reputation: 85

How to write a prolog mathematical Function?

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

Answers (2)

Timothy Murphy
Timothy Murphy

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

  • we need X to be greater than 0
  • we need the result of f(x-1) which we called V
  • V is the result of f(X-1) when func(X-1, V) is true
  • prolog doesn't allow expressions inside predicates so we state U is X-1
  • Then we put everything together and state Y is X *X + V

Upvotes: 3

Nicholas Carey
Nicholas Carey

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

Related Questions