I wrote the following program to check strings for balanced parenthesis:
isBalanced xs = isBalanced\' xs []
isBalanced\' [] [] = True
isBalanced\' [] _ = False
I think hammar's answer is the best, but here are smaller steps you can do - use null
and lookup
:
{-# LANGUAGE PatternGuards #-}
isBalanced xs = isBalanced' xs []
isBalanced' [] x = null x
isBalanced' (c:xs) ys | Just d <- lookup c par = isBalanced' xs (d:ys)
where par = [('(',')'), ('[',']'),('{','}')]
isBalanced' _ [] = False
isBalanced' (x:xs) (y:ys) = x == y && isBalanced' xs ysl
Your example positives
and negatives
data should definitely use map
, or even all
.