Advertisement
ulysses4ever

mmcs-olimp-2011-task1

Apr 27th, 2011
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- 1
  2. open2close '(' = ')'
  3. open2close '[' = ']'
  4. open2close '{' = '}'
  5. open2close '<' = '>'
  6.  
  7. close2open ')' = '('
  8. close2open ']' = '['
  9. close2open '}' = '{'
  10. close2open '>' = '<'
  11.  
  12. isOpen c = elem c "({[<"
  13.  
  14. complete str = impl str "" "" where
  15.     -- параметры impl: targetStringTail stack result
  16.     impl "" "" res = res
  17.     impl "" st res = res ++ map open2close st
  18.     impl (c:cs) "" res
  19.         | isOpen c = impl cs [c] (res ++ [c])
  20.         | otherwise = impl cs "" (res ++ [close2open c, c])    
  21.     impl (c:cs) st@(d:ds) res
  22.         | isOpen c = impl cs (c:st) (res ++ [c])
  23.         | otherwise =
  24.             if
  25.                 close2open c == d
  26.             then
  27.                 impl cs ds (res ++ [c])
  28.             else
  29.                 uncurry (impl cs) $ fix (close2open c) st res
  30.  
  31.  
  32. -- если встретили в строке неожиданную закрывающую скобку,
  33. -- пытаемся исправить это с помощью соовтетствующей
  34. -- открывающей скобки c из стека, если таковая была
  35. fix c st res
  36.     | not $ elem c st = (st, (res ++ [c, open2close c]))
  37.     | otherwise = (st', res ++ a' ++ [open2close c])
  38.         where
  39.             (a, b) = span (/= c) st
  40.             a' = reverse $ map open2close a
  41.            st' = tail b
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement