Re:A Brutal Look at Balanced Parentheses, Computing Machines...
by antidesitter on Friday February 22, 2019 @06:11PM
(#19230032)
Two purely-functional versions (written in Haskell):
A more general version with multiple types of brackets:
[ Parent
| on HN ]
Re:A Brutal Look at Balanced Parentheses, Computing Machines...
by Tarean on Saturday February 23, 2019 @06:02AM
(#19232730)
My naive version would be
import Control.Monad (foldM)
checkBalanced :: [Char] -> Bool
checkBalanced = isStackEmpty . foldM step mempty
where
step (x:xs) c
| x == c = Just xs
step ls c
| Just r <- inverse c = Just (r : ls)
step _ _ = Nothing
inverse = flip lookup [( '(', ')' )]
isStackEmpty stack = stack == Just []