Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. {-|
  2. Module: Validator
  3. Description: Parses parenthesis variations for correct nesting.
  4.  
  5. Parses (), <>, {}, [] etc for correct nesting, open and closing.
  6.  
  7. Usage:
  8.  
  9. $ validator '[<>{()}]'
  10. [<>{()}]
  11. Found valid characters in valid form.
  12.  
  13. $ validator '[<><><>]'
  14. [<><><>]
  15. Found valid characters in valid form.
  16.  
  17. $ validator '[<><><>]'
  18. [(]
  19. Valid characters but invalid form.
  20.  
  21. $ validator '[z]'
  22. [z]
  23. Invalid characters detected, please limit it to ()<>[]{}
  24. -}
  25. module Main where
  26.  
  27. import System.Environment
  28. import System.Exit
  29. import Data.Map.Strict(assocs, keys, Map, fromList, (!?), (!))
  30.  
  31. data ErrorCodes = NoError | InvalidInput | Invalid deriving (Show, Eq, Enum)
  32.  
  33. main :: IO ExitCode
  34. main = do
  35. inputChars <- getArgs
  36. let arg = head inputChars
  37. putStrLn arg
  38. if not (validArg arg)
  39. then do
  40. putStrLn ("Invalid characters detected, please limit it to " ++ validChars)
  41. exitWith (ExitFailure (fromEnum InvalidInput))
  42. else if validForm arg
  43. then do
  44. putStrLn "Found valid characters in valid form."
  45. exitSuccess
  46. else do
  47. putStrLn "Valid characters but invalid form."
  48. exitWith (ExitFailure (fromEnum Invalid))
  49.  
  50. validForm :: String -> Bool
  51. validForm chars
  52. | not ((mod (length chars) 2) == 0) = False
  53. | otherwise = validFormChecker chars ""
  54.  
  55. validFormChecker :: String -> String -> Bool
  56. validFormChecker chars stack
  57. | (length stack == 0) && (length chars == 0) = True
  58. | (isOpeningChar (head chars)) && ((validFormChecker (tail chars)) ([(head chars)] ++ stack)) = True
  59. | otherwise = (matchingPairs (head stack) (head chars)) && (validFormChecker (tail chars) (tail stack))
  60.  
  61. isOpeningChar :: Char -> Bool
  62. isOpeningChar currentChar = (currentChar `elem` (keys getPairs))
  63.  
  64. matchingPairs :: Char -> Char -> Bool
  65. matchingPairs a b = getPairs ! a == b
  66.  
  67. validChars :: String
  68. validChars = foldr combineChars [] (assocs getPairs)
  69.  
  70. combineChars :: (Char, Char) -> [Char] -> [Char]
  71. combineChars (char1, char2) keyPair = [char1] ++ [char2] ++ keyPair
  72.  
  73. getPairs :: Map Char Char
  74. getPairs = fromList [ ('[', ']')
  75. , ('{', '}')
  76. , ('(', ')')
  77. , ('<', '>')
  78. ]
  79.  
  80. validArg :: String -> Bool
  81. validArg receivedChars = let
  82. vc = validChars
  83. filteredChars = filter (\char -> char `elem` vc) receivedChars
  84. in (length receivedChars) == (length filteredChars)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement