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 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) | |
} |
or another way to do it with no rec, but has a flaw
def balance(s: String): Boolean ={
return s.toList.map(c => {
c match {
case '(' => 1
case ')' => -1
case _ => 0
}
}).sum == 0
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
another way to write that using match and tailrec