How do I write a prologue math function?

I am trying to convert a math function to a prologue but I keep getting the error. Can anyone give me a hint what, where is my mistake please?

I want to convert f (x) = x 2 + f (x - 1). So I assume this is a recursive procedure. Here's what I've 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.

+3


source to share


2 answers


Prolog works using predicate calculus. The predicate can evaluate to true or false.

You need to write what is true (everything else is considered false, since the prologue interpreters will use a closed world guess).

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 the prologue 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 considered to say your predicate func is true when X is 0 and Y is 0

This will be your main case. (You only need one, since you only have 1 recursive call).

Next up is your recursive case:

When func is true for generic X

  • we need X to be greater than 0
  • we need the result f (x-1), which we named V
  • V is the result of f (X-1) when func (X-1, V) is true
  • prologue does not allow expression inside predicates, so we indicate that U is X-1
  • Then we put everything together and the Y state is X * X + V
+3


source


Try the following:



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!

      

+2


source







All Articles