Search code examples
prologunification

What's an elegant way to unify X,Y with (1,2), (1,-2), (-1,2), (-1,-2), (2,1), (2,-1) , (-2,1), (-2,-1)?


What's an elegant way to unify X,Y with (1,2), (1,-2), (-1,2), (-1,-2), (2,1), (2,-1) , (-2,1), (-2,-1)?

Doing it this way seems error prone and tedious:

foo(1,2).
foo(1,-2).
foo(-1,-2).
...
...
...

And this way seems too expensive:

foo(X,Y) :-
  L = [1,-1,2,-2],
  member(X,L),
  member(Y,L),
  abs(X,X1), abs(Y,Y1),
  X1 =\= Y1.

Solution

  • A further development on what was commented:

    generate_pairs_foo(X,Y) :-
      L = [1,-1,2,-2],
      member(X,L),
      member(Y,L),
      abs(X,X1), abs(Y,Y1),
      X1 =\= Y1.
    
    assert_all_foo([]).
    
    assert_all_foo([(X,Y)|T]) :-
      assert(foo(X,Y)), assert_all_foo(T).
    
    find_all((X,Y),generate_pairs_foo(X,Y),L), assert_all_foo(L).
    

    Hmmmmmm... look, it's easier and shorter to just write all the cases xD