Created
June 18, 2016 01:32
-
-
Save terakilobyte/f7e29e268c333395012f66b9fbe7374f 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([], [], 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, Map.get(@matches, h_list) == h_open) | |
true -> | |
parse_for_balanced_brackets(t_list, [h_list | [ h_open | t_open ]], balanced) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment