Search code examples
prologlinear-programminginstantiation-error

Solving linear programming with Prolog


I am trying to solve first linear programming problem example on http://www.zweigmedia.com/RealWorld/tutorialsf4/framesLinProGr.html. X and Y are zero or positives, their sum can be upto 50, 2X+Y can be upto 60. The function X+3Y has to be maximized.

I am using following code:

mysol2(X,Y,Z):-
    X in 0..sup,  % Error: Syntax error: Operator expected
    Y in 0..sup,
    X + Y =< 50,
    2 * X + Y =< 60,
    Z is max(X + 3*Y).

However, it does not even load (error is indicated above).

With following code:

mysol2(X,Y,Z):-
    X >= 0,
    Y >= 0,
    X + Y =< 50,
    2 * X + Y =< 60,
    Z is max(X + 3*Y).

The program loads, but on running:

ERROR: >=/2: Arguments are not sufficiently instantiated

How can I correct these errors?


Solution

  • (>=)/2 and (is)/2 are very low-level predicates. You can only use them in very special circumstances. In most cases, these predicates will lead to instantiation errors because one or both arguments are not sufficiently instantiated.

    Constraints are a declarative solution in such cases, working correctly in all cases.

    For example, you can use CLP(Q) as available in SICStus Prolog with minimal modifications of your code:

    :- use_module(library(clpq)).
    
    solution(X, Y) :-
        { X >= 0,
          Y >= 0,
          X + Y =< 50,
          2*X + Y =< 60 }.
    

    Sample query and result:

    | ?- solutionX, Y), maximize(X+3*Y).
    X = 0,
    Y = 50  ? ;
    no
    

    The most widely used Prolog and Prolog-like systems (SICStus, ECLiPSe etc.) all ship with powerful constraint libraries, which are meant to be used notably when reasoning over integers and rationals.