Programming Praxis – Balanced Delimiters

In today’s Programming Praxis exercise, our goal is to determine whether the delimiters in a given string are balanced. Let’s get started, shall we?

The exercise mentions that parser generators are useful for this exercise, but since the grammar isn’t very complicated I’m just going to use the straightforward method of pushing the delimiters onto a stack.

balanced :: String -> Bool
balanced = f [] where
    f bs       [] = null bs
    f bs       ('\\':_:cs) = f bs cs
    f (b:bs)   (c   :  cs) | lookup b pairs == Just c           = f bs cs
                           | elem b "'\""                       = f (b:bs) cs
    f bs       (c   :  cs) | any (\(a,b) -> elem c [a,b]) pairs = f (c:bs) cs 
                           | otherwise                          = f bs cs
    pairs = [('(', ')'), ('[', ']'), ('{', '}'), ('\'', '\''), ('"', '"')]

Some tests to see if everything is working properly:

main :: IO ()
main = do print . and $ map balanced ["", "abc", "()", "[[[]]]", "'('", "\\(()"]
          print . and $ map (not . balanced) ["(", "([)]", "'{'}", "\\()"]
About these ads

Tags: , , , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 35 other followers

%d bloggers like this: