Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {-|
- Module: Validator
- Description: Parses parenthesis variations for correct nesting.
- Parses (), <>, {}, [] etc for correct nesting, open and closing.
- Usage:
- $ validator '[<>{()}]'
- [<>{()}]
- Found valid characters in valid form.
- $ validator '[<><><>]'
- [<><><>]
- Found valid characters in valid form.
- $ validator '[<><><>]'
- [(]
- Valid characters but invalid form.
- $ validator '[z]'
- [z]
- Invalid characters detected, please limit it to ()<>[]{}
- -}
- module Main where
- import System.Environment
- import System.Exit
- import Data.Map.Strict(assocs, keys, Map, fromList, (!?), (!))
- data ErrorCodes = NoError | InvalidInput | Invalid deriving (Show, Eq, Enum)
- main :: IO ExitCode
- main = do
- inputChars <- getArgs
- let arg = head inputChars
- putStrLn arg
- if not (validArg arg)
- then do
- putStrLn ("Invalid characters detected, please limit it to " ++ validChars)
- exitWith (ExitFailure (fromEnum InvalidInput))
- else if validForm arg
- then do
- putStrLn "Found valid characters in valid form."
- exitSuccess
- else do
- putStrLn "Valid characters but invalid form."
- exitWith (ExitFailure (fromEnum Invalid))
- validForm :: String -> Bool
- validForm chars
- | not ((mod (length chars) 2) == 0) = False
- | otherwise = validFormChecker chars ""
- validFormChecker :: String -> String -> Bool
- validFormChecker chars stack
- | (length stack == 0) && (length chars == 0) = True
- | (isOpeningChar (head chars)) && ((validFormChecker (tail chars)) ([(head chars)] ++ stack)) = True
- | otherwise = (matchingPairs (head stack) (head chars)) && (validFormChecker (tail chars) (tail stack))
- isOpeningChar :: Char -> Bool
- isOpeningChar currentChar = (currentChar `elem` (keys getPairs))
- matchingPairs :: Char -> Char -> Bool
- matchingPairs a b = getPairs ! a == b
- validChars :: String
- validChars = foldr combineChars [] (assocs getPairs)
- combineChars :: (Char, Char) -> [Char] -> [Char]
- combineChars (char1, char2) keyPair = [char1] ++ [char2] ++ keyPair
- getPairs :: Map Char Char
- getPairs = fromList [ ('[', ']')
- , ('{', '}')
- , ('(', ')')
- , ('<', '>')
- ]
- validArg :: String -> Bool
- validArg receivedChars = let
- vc = validChars
- filteredChars = filter (\char -> char `elem` vc) receivedChars
- in (length receivedChars) == (length filteredChars)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement