Created
January 18, 2021 22:55
-
-
Save googleson78/a9f838cc77ca9269b43d95b9a80d30e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE LambdaCase #-} | |
import Control.Monad.Trans.Reader (runReader, local, ask, Reader) | |
import Data.Maybe (mapMaybe) | |
data Paren = LParen | RParen | |
balanced :: [Paren] -> Bool | |
balanced xs = flip runReader 0 $ go xs | |
where | |
go :: [Paren] -> Reader Int Bool | |
go [] = do | |
n <- ask | |
pure $ n == 0 | |
go (par:pars) = do | |
curr <- ask | |
if curr < 0 | |
then pure False | |
else local (+ count par) $ go pars | |
count :: Paren -> Int | |
count LParen = 1 | |
count RParen = -1 | |
fromChar :: Char -> Maybe Paren | |
fromChar = \case | |
'(' -> Just LParen | |
')' -> Just RParen | |
_ -> Nothing | |
parensOnly :: String -> [Paren] | |
parensOnly = mapMaybe fromChar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment