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.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Haskell
I am by no means an expert in Haskell, just an enthusiast. Feel free to help me improve this code!
Try it.