Created
February 18, 2012 18:23
-
-
Save ijt/1860533 to your computer and use it in GitHub Desktop.
Check for balanced parentheses in a SQL statement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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