Created
November 19, 2014 12:33
-
-
Save matthiasbeyer/9bca2a95c8fb66997f21 to your computer and use it in GitHub Desktop.
Stack-based bracket matcher in Haskell
This file contains 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
module Main | |
where | |
data Node = Node { chr :: Char | |
, next :: Maybe Node } | |
deriving (Show) | |
prepareInput :: String -> String | |
prepareInput str = filter (\c -> c `elem` ['(', ')']) str | |
processChar :: Char -> String -> Maybe Node -> Maybe Node | |
processChar '(' "" Nothing = Just (Node '(' Nothing) -- init case | |
processChar ')' r (Just n) = process r (next n) | |
processChar ')' _ Nothing = Just (Node ')' Nothing) -- error, generate a dummy | |
processChar '(' r stack = process r (Just (Node '(' stack)) | |
-- Todo: Integrate this function into the `process` function as soon as it | |
-- works. | |
process :: String -> Maybe Node -> Maybe Node | |
process [] Nothing = Nothing | |
process [] stack = stack | |
process str stack = processChar (head str) (tail str) stack | |
-- We actually don't care when `stack` is Nothing and pass it to the | |
-- `processChar` function | |
answer :: Maybe Node -> String | |
answer Nothing = "OK" | |
answer _ = "Nup" | |
main :: IO () | |
main = do | |
str <- getLine | |
putStrLn $ answer $ process (prepareInput str) Nothing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compare with: https://gist.github.com/Heimdell/3f483c02226d95faf1ee
Use specialized solutions for parsing - Parsec/Attoparsec/ReadP/Whatever.