Skip to content

Instantly share code, notes, and snippets.

@mohnoor94
Created March 3, 2018 21:58
Show Gist options
  • Select an option

  • Save mohnoor94/db920bf261a5fce184b999d156adc06f to your computer and use it in GitHub Desktop.

Select an option

Save mohnoor94/db920bf261a5fce184b999d156adc06f to your computer and use it in GitHub Desktop.
Functional Programming Principles in Scala - Exercise 2: Parentheses Balancing
/**
* Exercise 2
*/
def balance(chars: List[Char]): Boolean = {
def difference(acc: Int, ch: List[Char]): Int = {
val head = ch.head
val tail = ch.tail
val isLeft = head == '('
val isRight = head == ')'
val notEmptyTail = tail.nonEmpty
if (acc == 1) -1
else if (!isLeft && !isRight)
if (notEmptyTail) difference(acc, tail) else acc
else if (isLeft)
if (notEmptyTail) difference(acc - 1, tail) else acc - 1
else if (notEmptyTail) difference(acc + 1, tail) else acc + 1
}
difference(0, chars) == 0
}
@mohnoor94
Copy link
Author

This exercise is copied from the Functional Programming Principles in Scala course, week 1. Find more on my website.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment