Skip to content

Instantly share code, notes, and snippets.

@matthiasbeyer
Created November 19, 2014 12:33
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 matthiasbeyer/9bca2a95c8fb66997f21 to your computer and use it in GitHub Desktop.
Save matthiasbeyer/9bca2a95c8fb66997f21 to your computer and use it in GitHub Desktop.
Stack-based bracket matcher in Haskell
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
@Heimdell
Copy link

Compare with: https://gist.github.com/Heimdell/3f483c02226d95faf1ee

Use specialized solutions for parsing - Parsec/Attoparsec/ReadP/Whatever.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment