Created
June 18, 2016 01:49
-
-
Save terakilobyte/2f4ca9ee5b68789c8223d013caa93406 to your computer and use it in GitHub Desktop.
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
defmodule BracketPush do | |
@doc """ | |
Checks that all the brackets and braces in the string are matched correctly, and nested correctly | |
""" | |
@matches %{"}"=> "{", ")"=> "(", "]"=> "["} | |
@opening ["{", "(", "["] | |
@spec check_brackets(String.t) :: boolean | |
def check_brackets(""), do: true | |
def check_brackets(str) do | |
str | |
|> String.replace(~r/[^\(|\{\[|\]|\}|\)]/, "") | |
|> String.split("", trim: true) | |
|> parse_for_balanced_brackets | |
end | |
@spec parse_for_balanced_brackets(List.t, List.t, boolean) :: boolean | |
defp parse_for_balanced_brackets(list, openers \\ [], balanced \\ true) | |
defp parse_for_balanced_brackets(_, _, false), do: false | |
defp parse_for_balanced_brackets([], [], balanced), do: balanced | |
defp parse_for_balanced_brackets([], list, _), do: false | |
defp parse_for_balanced_brackets([h_list | t_list], [], balanced) do | |
case Enum.member?(@opening, h_list) do | |
false -> | |
parse_for_balanced_brackets([], [], false) | |
true -> | |
parse_for_balanced_brackets(t_list, [h_list], balanced) | |
end | |
end | |
defp parse_for_balanced_brackets([h_list | t_list], [h_open | t_open], balanced) do | |
case Enum.member?(@opening, h_list) do | |
false -> | |
parse_for_balanced_brackets(t_list, t_open, is_bracket_match(h_list, h_open)) | |
true -> | |
parse_for_balanced_brackets(t_list, [h_list | [ h_open | t_open ]], balanced) | |
end | |
end | |
@spec is_bracket_match(String.t, String.t) :: boolean | |
defp is_bracket_match(a, b) do | |
Map.get(@matches, a) == b | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment