Balanced brackets: Difference between revisions

→‎{{header|Haskell}}: added automaton solution
(→‎{{header|Haskell}}: added automaton solution)
Line 3,157:
 
=={{header|Haskell}}==
The simplest solution exploits the idea of stack-based automaton, which could be implemented by a fold.
<lang haskell>
isMatching :: String -> Bool
isMatching = null . foldl aut []
where
aut ('[':s) ']' = s
-- aut ('{':s) '}' = s -- automaton could be extended
aut s x = x:s
</lang>
 
This generates an infinite stream of correct balanced brackets expressions:
 
<lang haskell>
brackets = filter isMatching
$ [1.. ] >>= (`replicateM` "[]{}")
</lang>
 
 
In case the index of unmatched opening bracket is need to be found, following solution is suitable.
 
<lang haskell>
import Control.Monad
Anonymous user