Checking if a string consists of balanced parenthesis

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

    I think hammar's answer is the best, but here are smaller steps you can do - use null and lookup:

    {-# LANGUAGE PatternGuards #-}
    isBalanced xs = isBalanced' xs []
    
    isBalanced' [] x = null x
    
    isBalanced' (c:xs) ys | Just d <- lookup c par = isBalanced' xs (d:ys)
      where par = [('(',')'), ('[',']'),('{','}')]
    
    isBalanced' _  [] = False
    
    isBalanced' (x:xs) (y:ys) = x == y && isBalanced' xs ysl
    

    Your example positives and negatives data should definitely use map, or even all.

提交回复
热议问题