Skip to content

Instantly share code, notes, and snippets.

@GeoffChurch
Last active May 20, 2022 17:54
Show Gist options
  • Save GeoffChurch/79381cf27c9bd3717aebe935763b6081 to your computer and use it in GitHub Desktop.
Save GeoffChurch/79381cf27c9bd3717aebe935763b6081 to your computer and use it in GitHub Desktop.
coalesce_variables/1 applies an equivalence relation to the variables of a term.
eos([], []).
% Relates a list to a partitioning of its elements into two subsequences (append/3 for subsequences).
list_subseq_subseq([]) --> eos.
list_subseq_subseq([H|S]) --> [H], list_subseq_subseq(S).
list_subseq_subseq([H|S]), [H] --> list_subseq_subseq(S).
% Relates a list to a partitioning of its elements into nonempty subsequences (append/2 for nonempty subsequences).
list_subseqs([], []).
list_subseqs([H|T], [[H|PT]|Ps]) :-
call_dcg((list_subseq_subseq(T), list_subseqs), PT, Ps).
all_equal(Xs) :- maplist(=(_), Xs).
% Applies an equivalence relation to the variables of T.
coalesce_variables(T) :-
call_dcg((term_variables, list_subseqs), T, Parts),
maplist(all_equal, Parts).
% Example:
% ?- T = f(A, B, C), coalesce_variables(T).
% T = f(C, C, C),
% A = B, B = C ;
% T = f(B, B, C),
% A = B ;
% T = f(C, B, C),
% A = C ;
% T = f(A, C, C),
% B = C ;
% T = f(A, B, C).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment