Skip to content

Instantly share code, notes, and snippets.

@ijt
Created February 18, 2012 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ijt/1860533 to your computer and use it in GitHub Desktop.
Save ijt/1860533 to your computer and use it in GitHub Desktop.
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