Created
May 25, 2020 17:34
-
-
Save jdan/174968be834f19b94244586c702e7b73 to your computer and use it in GitHub Desktop.
Balanced parentheses with prolog
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
?- balanced_parens(Q). | |
Q = "" ; | |
Q = "()" ; | |
Q = "(())" ; | |
Q = "((()))" ; | |
Q = "(()())" ; | |
Q = "(((())))" ; | |
Q = "((()()))" ; | |
Q = "(()(()))" ; | |
Q = "(()()())" ; | |
Q = "((())())" ; | |
Q = "(()()())" ; | |
Q = "((((()))))" ; | |
Q = "(((()())))" ; | |
Q = "((()(())))" ; | |
Q = "((()()()))" ; | |
Q = "(((())()))" ; | |
Q = "((()()()))" . |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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