Skip to content

Instantly share code, notes, and snippets.

@sumerman
Created May 27, 2012 09:07
Show Gist options
  • Save sumerman/2802975 to your computer and use it in GitHub Desktop.
Save sumerman/2802975 to your computer and use it in GitHub Desktop.
Solution for a classic balanced-parens problem
{-
Bal ::= (Bal)Bal | [Bal]Bal | ""
-}
import Control.Monad
brackets = [('[',']'), ('(',')')]
isObr b = elem b (map fst brackets)
isCoBr b1 b2 = elem (b1,b2) brackets || elem (b2,b1) brackets
balanced (x:xs) | isObr x =
balanced >=> closing x >=> balanced $ xs
where
closing x (y:ys) | isCoBr x y = return ys
closing _ _ = mzero
balanced x = return x
check = maybe False null . balanced
main = do
s <- getLine
print $ check s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment