Last active
July 24, 2018 20:37
-
-
Save f0ster/592cd1dad56a13c29a5559e88f806484 to your computer and use it in GitHub Desktop.
verifying balanced parens with recursion
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
def balance(chars: List[Char]): Boolean = { | |
def balanced(chars: List[Char], currently_open_parens: Int): Boolean = { | |
if (chars.isEmpty) currently_open_parens == 0 | |
else { | |
if(chars.head == '(') balanced(chars.tail, currently_open_parens+1) | |
else { | |
if(chars.head == ')' ) { | |
currently_open_parens > 0 && balanced(chars.tail, currently_open_parens-1) | |
} else balanced(chars.tail, currently_open_parens) | |
} | |
} | |
} | |
balanced(chars,0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
or another way to do it with no rec, but has a flaw