Created
December 23, 2016 18:08
-
-
Save jesperp/9ab60cddd3a3a50f4ecaf3df7e712959 to your computer and use it in GitHub Desktop.
This file contains 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
-module(bracketpush). | |
-export([check_brackets/1]). | |
check_brackets(Str) -> | |
check_brackets(Str, []). | |
% Base cases | |
check_brackets([], []) -> true; | |
check_brackets([], _Acc) -> false; | |
% Opening brackets | |
check_brackets([Bracket | Tail], Acc) when Bracket == ${ ; Bracket == $( ; Bracket == $[ -> | |
check_brackets(Tail, [Bracket|Acc]); | |
% Closing brackets | |
check_brackets([Bracket | Tail], [Prev | Acc]) when | |
Prev == $( andalso Bracket == $) ; | |
Prev == $[ andalso Bracket == $] ; | |
Prev == ${ andalso Bracket == $} | |
-> check_brackets(Tail, Acc); | |
check_brackets([Bracket | _Tail], _Acc) when Bracket == $} ; Bracket == $) ; Bracket == $] -> | |
false; | |
% Ignore other cases | |
check_brackets([_|Tail], Acc) -> check_brackets(Tail, Acc). |
This file contains 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
-module(bracketpush_tests). | |
-include_lib("eunit/include/eunit.hrl"). | |
% Run using: erl -make && erl -noshell -eval "eunit:test(bracketpush, [verbose])" -s init stop | |
empty_string_test() -> | |
?assert(bracketpush:check_brackets("")). | |
appropriate_bracketing_in_a_set_of_brackets_test() -> | |
?assert(bracketpush:check_brackets("{}")). | |
unclosed_brackets_test() -> | |
?assertNot(bracketpush:check_brackets("{{")). | |
more_than_one_pair_of_brackets_test() -> | |
?assert(bracketpush:check_brackets("{}[]")). | |
brackets_are_out_of_order_test() -> | |
?assertNot(bracketpush:check_brackets("}{")). | |
nested_brackets_test() -> | |
?assert(bracketpush:check_brackets("{[()]}")). | |
unbalanced_nested_brackets_test() -> | |
?assertNot(bracketpush:check_brackets("{[}]")). | |
bracket_closure_with_deeper_nesting_test() -> | |
?assertNot(bracketpush:check_brackets("{[)][]}")). | |
bracket_closure_in_a_long_string_of_brackets_test() -> | |
?assert(bracketpush:check_brackets("{[]([()])}")). | |
should_ignore_non_bracket_characters_test() -> | |
?assert(bracketpush:check_brackets("{hello[]([a()])b}c")). | |
string_with_newlines_test() -> | |
?assert(bracketpush:check_brackets("[]\n{()}\n[(({}))]\n")). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment