Mitsos
Mitsos

Reputation: 19

Prolog, predicate that swaps 1 to 0 and 0 to 1 and puts them in a list

New to Prolog. I want a program that swaps 1 to 0 and 0 to 1 and answers that question:

?- swap([1,1,0,1,0,0,0,1], L2).
L2 = [0,0,1,0,1,1,1,0]

Upvotes: 1

Views: 276

Answers (2)

Fatalize
Fatalize

Reputation: 3543

A CLPFD solution that works properly in all directions, for reference:

:- use_module(library(clpfd)).

swap(X, Y) :-
    maplist(#\=, X, Y),
    X ins 0..1,
    Y ins 0..1.

Specifically:

?- swap(X,Y).
X = Y, Y = [] ;
X = [_2640],
Y = [_2658],
_2640 in 0..1,
_2640#\=_2658,
_2658 in 0..1 ;
X = [_3200, _3206],
Y = [_3224, _3230],
_3200 in 0..1,
_3200#\=_3224,
_3224 in 0..1,
_3206 in 0..1,
_3206#\=_3230,
_3230 in 0..1 ;
…

works properly, when swap/2 from the other answer does not:

?- swap2(X,Y).
X = Y, Y = [] ;
X = [0],
Y = [1] ;
X = [0, 0],        % Doesn't enumerate ([1],[0]), etc.
Y = [1, 1] ;
X = [0, 0, 0],
Y = [1, 1, 1] ;
…

Upvotes: 3

danlei
danlei

Reputation: 14291

complement(0, 1).
complement(1, 0).

swap(X, Y) :- maplist(complement, X, Y).

Upvotes: 6

Related Questions