3
votes

i'm new to prolog programing, and my first task is to make a quadratic equation solution finder. I have found and rewritten a input/output version of it, however i do not understand the usage of paranthesis. Do they work just as in C/C++? It seems to me as if they should be used every time i introduce a new variable being input by the user. Otherwise i keep getting specific error:
"ERROR: is/2: Arguments are not sufficiently instantiated" I looked up for a clear explanation of that problem, but haven't found a sufficient answer to my problem.

q :- write('A = '),
 read_integer(A),
 (   A = 0, write('Not a quadratic equation');
     write('B = '),
     read_integer(B),
     write('C = '),
     read_integer(C),
     D is B*B-4*A*C,
     (   D = 0, write('x = '), X is -B/2/A, write(X);
         D > 0, write('x1 = '), X1 is (-B+sqrt(D))/2/A, write(X1), nl, write('x2 = '), X2 is (-B-sqrt(D))/2/A, write(X2);
         D < 0, write('Delta < 0!')
     )
 ). q.

I do not know why it works only if I keep up paranthesis after reading A, and after making the equation for D value. Does it have something to do with their scope? What is instantiation in prolog then? Just to clarify, here's exactly what i have cut out:

q :- write('A = '),
 read(A),
   A = 0, write('Not a quadratic equation');
     write('B = '),
     read(B),
     write('C = '),
     read(C),
     D is B*B-4*A*C, 
        D = 0, write('x = '), X is -B/2/A, write(X);
         D > 0, write('x1 = '), X1 is (-B+sqrt(D))/2/A, write(X1), nl, write('x2 = '), X2 is (-B-sqrt(D))/2/A, write(X2);
       D < 0, write('Delta <0!'), nl, q.

Error:

A = 1.
B = |: 2.
C = |: 1.

ERROR: is/2: Arguments are not sufficiently instantiated
1

1 Answers

2
votes

Since Prolog is based on a different paradigm, it's rather obvious that tokens have different meaning. Removing the parenthesis you're changing the scoping of the disjunction operator ';'/2. Such operator is syntax sugar meant to simplify alternative branches inside a same clause. By default, clauses are conjunction of goals, expressed by the ','/2 operator. Once removed the parenthesis, SWI-Prolog warns about

Singleton variable in branch: D

Now is clearer what is the problem: the value you 'assigned' (we say to bind, instead of assign) with

D is B*B-4*A*C, 

has been forgotten when the execution has reached the goal D > 0,. Arithmetic evaluation, performed by operator '>'/2 on both arguments, requires instantiated variables to numeric values.