Advertisement
Guest User

Untitled

a guest
Jan 8th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Kata.BraceExpansion (expandBraces) where
  2.  
  3. getBraces :: String -> Maybe (Int, Int)
  4. getBraces str = if (start /= end && start /= -1) then (Just (start, end)) else Nothing
  5.   where
  6.   checkChar (start, end, i, braces) c
  7.     | start /= -1 && end /= -1 = (start, end, 0, 0)
  8.     | c == '{'  = (if (braces == 0) then i else start, end, i+1, braces+1)
  9.     | c == '}'  = (start, if (braces == 1) then i else end, i+1, braces-1)
  10.     | otherwise = (start, end, i+1, braces)
  11.   indices = foldl checkChar (-1, -1, 0, 0) str
  12.   start   = (\i -> case i of (x,_,_,_) -> x) indices
  13.   end     = (\i -> case i of (_,x,_,_) -> x) indices
  14.  
  15. extractOptions :: String -> [String]
  16. extractOptions str = res $ foldl f ("", [], 0) str where
  17.   f (w, ws, bs) c
  18.     | c == '{'  = ('{':w, ws, bs+1)
  19.     | c == '}'  = ('}':w, ws, bs-1)
  20.     | c == ','  = if bs == 0 then ("", (reverse w):ws, bs) else (',':w, ws, bs)
  21.     | otherwise = (c:w, ws, bs)
  22.   res (w,ws,_) = (reverse w):ws
  23.  
  24.  
  25. expandBraces :: String -> [String]
  26. expandBraces str = case (getBraces str) of
  27.   (Just (i, j)) -> mergeResults $ map expandBraces expanded where
  28.     mergeResults = (foldl (\res l -> res ++ l) ([]))
  29.     expanded     = [take i str ++ option ++ drop (j+1) str | option <- extractOptions (drop (i+1) . take (j) $ str)]
  30.   Nothing       -> [str]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement