Skip to content

Instantly share code, notes, and snippets.

@jdan
Created May 25, 2020 17:34
Show Gist options
  • Save jdan/174968be834f19b94244586c702e7b73 to your computer and use it in GitHub Desktop.
Save jdan/174968be834f19b94244586c702e7b73 to your computer and use it in GitHub Desktop.
Balanced parentheses with prolog
?- balanced_parens(Q).
Q = "" ;
Q = "()" ;
Q = "(())" ;
Q = "((()))" ;
Q = "(()())" ;
Q = "(((())))" ;
Q = "((()()))" ;
Q = "(()(()))" ;
Q = "(()()())" ;
Q = "((())())" ;
Q = "(()()())" ;
Q = "((((()))))" ;
Q = "(((()())))" ;
Q = "((()(())))" ;
Q = "((()()()))" ;
Q = "(((())()))" ;
Q = "((()()()))" .
append3(A, B, C, D) :-
append(A, B, AB),
append(AB, C, D).
balanced([]).
balanced(List) :-
append3([open], Inner, [close], List),
balanced(Inner).
balanced(List) :-
append(Left, Right, List),
Left \= [],
Right \= [],
balanced(Left),
balanced(Right).
% gross
parens_notation([], "").
parens_notation([open | T], S) :-
parens_notation(T, Tp),
string_concat("(", Tp, S).
parens_notation([close | T], S) :-
parens_notation(T, Tp),
string_concat(")", Tp, S).
balanced_parens(X) :-
balanced(L),
parens_notation(L, X).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment