0
votes

I am working on prolog and faced this scenario - In my query, I pass something like this:

?- query( 2*X + 3*Y >= 3*Z )

Now, what I would like to do is have the prolog program capture the inequality expression so that I can have the above inequality in variables like below:

variable 'Lhs' will have 2*X + 3*Y variable 'Rhs' will have 3*Z Now I want the inequality involved to be also assigned somewhere (in a variable called Opr??), so that saying something like Lhs Opr Rhs would mean exactly like saying "2*X + 3*Y >= 3*Z"..

This is a general form of the scenario that I am working on. I somehow want the "inequality" involved to be identified, so that I can use it later in my code.

I am working on Eclipse-CLP with IC library.

3

3 Answers

3
votes

You can do it with any prolog system, using the univ/2 operator:

parse_ops(Expr, Lhs, Rhs, Op):-
  Expr =.. [Op, Lhs, Rhs].

?- parse_ops(2*X + 3*Y >= 3*Z, Lhs, Rhs, Op).
Lhs = 2*X+3*Y,
Rhs = 3*Z,
Op = (>=).
2
votes

You can use univ to disassemble your inequaliy:

Eq =.. [Op,Lhs,Rhs],

This works in both directions.

0
votes

This should be able to simply do:

parse_query(LHS >= RHS, LHS, RHS).

?- parse_query(2*X + 3*Y >= 3*Z, LHS, RHS).
LHS=2*X + 3*Y 
RHS=3*Z

What you need to be concerned here with is order of operations the Parser uses when reading your query. Take a look at the op/3 operator for eclipse-clp and the op/3 operator doc for swi-prolog. Notice the precedence number for inequalities are higher than operators. This means that when the query (2*X +3*Y >=3*Z) is parsed, the >= operator becomes the functor. Try to use the display predicate to make this clear.

?- display(2*X + 3*Y >= 3*Z).
>=(+(*(2,X), *(3,Y)), *(3,Z))