Search code examples
listprologclpfd

Creating a list of lists in Prolog


I want to have a list of lists with constraints, here's my code written in SWI-Prolog:

List = [L1,L2,L3],
L1 = [X1, X2], L1 ins 1..4,
L2 = [Y1, Y2], L2 ins 1..4,
L3 = [Z1, Z2], L3 ins 1..4.

But, it gives ERROR:Type Error: integer expected.


Solution

  • Using library CLP(FD) in SWI-Prolog 7.1.11 I get:

    ?- use_module(library(clpfd)).
    %    library(pairs) compiled into pairs 0.00 sec, 22 clauses
    %   library(lists) compiled into lists 0.01 sec, 122 clauses
    %   library(occurs) compiled into occurs 0.00 sec, 14 clauses
    %  library(apply_macros) compiled into apply_macros 0.02 sec, 175 clauses
    %  library(assoc) compiled into assoc 0.01 sec, 103 clauses
    % library(clpfd) compiled into clpfd 0.18 sec, 2,848 clauses
    true.
    
    ?- List = [L1,L2,L3],
    L1 = [X1, X2], L1 ins 1..4,
    L2 = [Y1, Y2], L2 ins 1..4,
    L3 = [Z1, Z2], L3 ins 1..4.
    List = [[X1, X2], [Y1, Y2], [Z1, Z2]],
    L1 = [X1, X2],
    L2 = [Y1, Y2],
    L3 = [Z1, Z2],
    X1 in 1..4,
    X2 in 1..4,
    Y1 in 1..4,
    Y2 in 1..4,
    Z1 in 1..4,
    Z2 in 1..4.
    

    Maybe the error was due to the dot instead of a comma at the end of the first line (corrected now)?