You are on page 1of 1

MSU-Iligan Institute of Technology

CSC 102
First Semeter 2014
Machine Problem 2
Parentheses Balancing . 100 points.
rite a recursi!e function "hich !erifies the balancing of #arentheses in a string$ "hich "e re#resent
as a List[Char] not a String% For e&am#le$ the function shoul' return true for the follo"ing
strings(
)if )*ero+ &, ma& )- 1 &,,
I tol' him )that it.s not )yet, 'one,% )/ut he "asn.t listening,
The function shoul' return false for the follo"ing strings(
(,
),,)
The last e&am#le sho"s that it.s not enough to !erify that a string contains the same number of o#ening
an' closing #arentheses%
0o this e&ercise by im#lementing the balance function in Main.scala% Its signature is as follo"s(
def balance(chars: List[Char]): Boolean
There are three metho's on List[Char] that are useful for this e&ercise(
chars.isEmpty: Boolean returns "hether a list is em#ty
chars.head: Char returns the first element of the list
chars.tail: List[Char] returns the list "ithout the first element
Hint( you can 'efine an inner function if you nee' to #ass e&tra #arameters to your function%
Testing( 1ou can use the toList metho' to con!ert from a String to a 2ist3Char4 ( e%g% "(just
an) example".toList%
C
y
r
u
s

G
.

G
a
b
i
l
l
a

You might also like