Checking if a string consists of balanced parenthesis

后端 未结 4 2316
渐次进展
渐次进展 2021-02-20 04:01

I wrote the following program to check strings for balanced parenthesis:

isBalanced xs = isBalanced\' xs []

isBalanced\' [] [] = True
isBalanced\' [] _  = False         


        
4条回答
  •  广开言路
    2021-02-20 04:22

    As Henning said, parser combinators would work for this. Here's an example using Parsec:

    import Text.Parsec
    
    grammar = many braces >> return ()
        where braces = choice [ between (char '(') (char ')') grammar
                              , between (char '[') (char ']') grammar
                              , between (char '{') (char '}') grammar
                              ]
    
    isBalanced :: String -> Bool
    isBalanced input = case parse (grammar >> eof) "" input of
                           Left  _ -> False
                           Right _ -> True
    

提交回复
热议问题