Dutch flag
Description
A solution to the Dutch flag problem
Source: The Art of Prolog
Download
Listing
/*
dutch(Xs,RedsWhitesBlues) :-
RedsWhitesBlues is a list of elements of Xs ordered
by color: red, then white, then blue.
*/
dutch(Xs,RedsWhitesBlues) :-
distribute(Xs,Reds,Whites,Blues),
append(Whites,Blues,WhitesBlues),
append(Reds,WhitesBlues,RedsWhitesBlues).
/*
distribute(Xs,Reds,Whites,Blues) :-
Reds, Whites, and Blues are the lists of red, white,
and blue elements in Xs, respectively.
*/
distribute([red(X)|Xs],[red(X)|Reds],Whites,Blues) :-
distribute(Xs,Reds,Whites,Blues).
distribute([white(X)|Xs],Reds,[white(X)|Whites],Blues) :-
distribute(Xs,Reds,Whites,Blues).
distribute([blue(X)|Xs],Reds,Whites,[blue(X)|Blues]) :-
distribute(Xs,Reds,Whites,Blues).
distribute([],[],[],[]).
% Program 15.5: A solution to the Dutch flag problem