DEV Community

Discussion on: Daily Challenge #151 - Reverse Parentheses

Collapse
 
aminnairi profile image
Amin • Edited

Haskell

I am by no means an expert in Haskell, just an enthusiast. Feel free to help me improve this code!

hasParens :: String -> Bool
hasParens string =
    elem '(' string && elem ')' string

takeBeforeParen :: String -> String
takeBeforeParen string =
    takeWhile (/= '(') string

takeAfterParen :: String -> String
takeAfterParen string =
    reverse $ takeWhile (/= ')') $ reverse string

takeInsideParens :: String -> String
takeInsideParens string =
    drop 1 $ dropWhile (/= '(') $ reverse $ drop 1 $ dropWhile (/= ')') $ reverse string

reverseInParens' :: String -> String
reverseInParens' string
    | hasParens string  = reverse end ++ "(" ++ reverseInParens middle ++ ")" ++ reverse start
    | otherwise         = reverse string
    where
        start   = takeBeforeParen string
        middle  = takeInsideParens string
        end     = takeAfterParen string

reverseInParens :: String -> String
reverseInParens string
    | hasParens string  = start ++ "(" ++ reverseInParens' middle ++ ")" ++ end
    | otherwise         = string
    where
        start   = takeBeforeParen string
        middle  = takeInsideParens string
        end     = takeAfterParen string

main :: IO ()
main = do
    print $ reverseInParens "hello"                     -- "hello"
    print $ reverseInParens "h(el)lo"                   -- "h(le)lo"
    print $ reverseInParens "a ((d e) c b)"             -- "a (b c (d e))"
    print $ reverseInParens "one (two (three) four)"    -- "one (rouf (three) owt)"
    print $ reverseInParens "one (ruof ((rht)ee) owt)"  -- "one (two ((thr)ee) four)"
    print $ reverseInParens ""                          -- ""                        -- ""

Try it.