-
Notifications
You must be signed in to change notification settings - Fork 0
/
valid-parentheses.hs
29 lines (26 loc) · 987 Bytes
/
valid-parentheses.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
module Main where
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
isValid :: [Char] -> Bool
isValid str = isValidAccum str [] where
isValidAccum [] [] = True
isValidAccum [] _ = False
isValidAccum (h:r) stack
| isOpen h = isValidAccum r (h:stack)
| isClose h = if (not $ null stack) && (getCounterPart $ head stack) == h
then isValidAccum r (tail stack)
else False where
isOpen c = c `Set.member` openPars
isClose c = c `Set.member` closePars
getCounterPart p = let (Just v) =
Map.lookup
p
(Map.fromList [('(',')'), ('[',']'), ('{','}')])
in v
openPars = Set.fromList ['(', '[', '{']
closePars = Set.fromList [')', ']', '}']
main :: IO ()
main = do
putStrLn $ show $ isValid "()[]{}"
putStrLn $ show $ isValid "(]"
putStrLn $ show $ isValid "{[]}"