Search code examples
prologinstantiation-error

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

Solution

  • 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
     ).