Skip to content

Instantly share code, notes, and snippets.

@ijt ijt/check_balance.hs
Created Feb 18, 2012

Embed
What would you like to do?
Check for balanced parentheses in a SQL statement
#!/usr/bin/env runhaskell
{-# LANGUAGE TemplateHaskell #-}
import Test.QuickCheck ((==>), Property)
import Test.QuickCheck.All (quickCheckAll)
-- main = interact $ show . checkBalance
main = $quickCheckAll
checkBalance :: String -> Bool
checkBalance s = checkBalance2 0 s
-- |checkBalance2 parenCount sql returns true if the given sql statement
-- fragment has balanced parens, given the parenCount to the left.
checkBalance2 :: Int -> String -> Bool
checkBalance2 0 "" = True
checkBalance2 _ "" = False
checkBalance2 n ('(':rest) = checkBalance2 (n + 1) rest
checkBalance2 n (')':rest) | n == 0 = False
| otherwise = checkBalance2 (n - 1) rest
checkBalance2 n ('\'':rest) = checkBalance2 n (drop 1 $ dropWhile (/= '\'') rest)
checkBalance2 n ('"':rest) = checkBalance2 n (drop 1 $ dropWhile (/= '"') rest)
checkBalance2 n (c:rest) = checkBalance2 n rest
prop_allLeftsFalse n = n > 0 && n < 100000 ==> checkBalance s == False
where s = replicate n '('
prop_allRightsFalse n = n > 0 && n < 100000 ==> checkBalance s == False
where s = replicate n ')'
prop_simpleBalance n = n >= 0 && n < 100000 ==> checkBalance s == True
where s = replicate n '(' ++ replicate n ')'
prop_wrongOrder n = n > 0 && n < 100000 ==> checkBalance s == False
where s = replicate n ')' ++ replicate n '('
prop_quotedStringsAreBalanced s = checkBalance s2 == True
where s2 = "'" ++ filter (/= '\'') s ++ "'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.