Checking if a string consists of balanced parenthesis

后端 未结 4 2409
渐次进展
渐次进展 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:27

    Using a left fold

    import Data.List (foldl')
    
    isBalanced xs = null $ foldl' op [] xs
      where
        op ('(':xs) ')' = xs
        op ('[':xs) ']' = xs
        op ('{':xs) '}' = xs
        op xs x = x:xs
    

    The fold builds up a stack of previously encountered characters, stripping away any matches as it finds them. If you end up with an empty list, the string is balanced.

    Using a left fold in the Maybe monad

    The disadvantage of using a left fold is that the entire string must always be scanned through. It would be nice to abort the operation with a failure should a closing brace be found without a matching opening brace. Here's a version that does just that.

    import Control.Monad (foldM)
    
    isBalanced' xs = maybe False null $ foldM op [] xs
      where
        op ('(':xs) ')'          = Just xs
        op ('[':xs) ']'          = Just xs
        op ('{':xs) '}'          = Just xs
        op xs x | x `elem` ")]}" = Nothing
                | otherwise      = Just (x:xs)
    

提交回复
热议问题