RMachnik
RMachnik

Reputation: 3694

Resolve quadratic equation in prolog

I got problem with quadrating equation implementation in prolog. I know some basics but at same point I can not understand output of swish.swi console. I would appreciate any help or suggestions from your side about my errors.

delta(A, B, C, D):- D is B*B - 4*A*C.

equation(A,B,C,X):- D1<0,delta(A,B,C,D1),X is 0. % or false... but how to retur false there?
equation(A,B,C,X):- D1 =:= 0,delta(A,B,C,D1),X is -B/2*A. 
equation(A,B,C,X): D1>0,delta(A,B,C,D1),X is -B-sqrt(D1)/2*A.
equation(A,B,C,X): D1>0,delta(A,B,C,D1),X is -B+sqrt(D1)/2*A.

I am getting two errors there after runnign equation(2, 0, 1, X).

Full stop in clause-body?  Cannot redefine ,/2
</2: Arguments are not sufficiently instantiated

Upvotes: 2

Views: 3347

Answers (2)

VladGeo
VladGeo

Reputation: 11

At the last 2 predicates (the ones where D>0), you forgot to write "-" after ":". Your code works good, it was just a sintax error. Below I corrected the code for you:

delta(A, B, C, D):- D is B*B - 4*A*C.
equation(A,B,C,X):- D1<0, delta(A,B,C,D1), X is 0. 
equation(A,B,C,X):- D1 =:= 0, delta(A,B,C,D1), X is -B/2*A.
equation(A,B,C,X):- delta(A,B,C,D1), D1>0, X is ((-1*B-sqrt(D1))/2*A).
equation(A,B,C,X):- delta(A,B,C,D1), D1>0, X is ((-1*B+sqrt(D1))/2*A).

Upvotes: 1

CapelliC
CapelliC

Reputation: 60034

about

Arguments are not sufficiently instantiated

you must swap delta/4 and the test. Also, it's better to use if/then/else, to avoid recomputing the result:

equation(A,B,C,X) :-
 delta(A,B,C,D1),
 (  D1 < 0
 -> X is 0
 ;  D1 =:= 0
 -> X is -B/2*A
 ;  X is -B-sqrt(D1)/2*A
 ).

Upvotes: 0

Related Questions