Balanced brackets: Difference between revisions

→‎{{header|Haskell}}: Added a scanl example.
m (→‎{{header|Haskell}}: added sample output)
(→‎{{header|Haskell}}: Added a scanl example.)
Line 3,258:
Bad "]]][[[][][][[][]]["
^
</pre>
 
 
and '''scanl''' also yields a simple fit when we want the index of the tipping point:
 
<lang haskell>import Control.Applicative ((<|>))
import Data.List (findIndex, replicate, scanl)
import Data.List.Split (chunksOf)
import System.Random
 
-------------------- BALANCED BRACKETS -------------------
 
bracketProblemIndex :: String -> Maybe Int
bracketProblemIndex s =
findIndex (< 0) depths <|> unClosed
where
depths = nesting s
unClosed
| 0 /= last depths = Just $ pred (length s)
| otherwise = Nothing
 
nesting :: String -> [Int]
nesting = tail . scanl level 0
where
level n '[' = succ n
level n ']' = pred n
level n _ = n
 
--------------------------- TEST -------------------------
main :: IO ()
main = do
let g = mkStdGen 137
mapM_ (putStrLn . showProblem) $
chunksOf
6
(bracket <$> take 60 (randomRs (0, 1) g))
 
showProblem s =
case bracketProblemIndex s of
Just i -> s <> ": Unmatched\n" <> replicate i ' ' <> "^"
_ -> s <> ": OK\n"
 
bracket :: Int -> Char
bracket 0 = '['
bracket _ = ']'</lang>
{{Out}}
<pre>]][]][: Unmatched
^
][[][[: Unmatched
^
][][[[: Unmatched
^
]][][]: Unmatched
^
[[][]]: OK
 
]]][]]: Unmatched
^
[][][[: Unmatched
^
[]]]]]: Unmatched
^
][[][[: Unmatched
^
[][]][: Unmatched
^
</pre>
 
9,659

edits