Guest User

xvi

a guest
Jan 8th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Codewars.Kata.Format where
  2. import Data.Char
  3.  
  4. format :: String -> Int -> String
  5. format str n = if length str <= n then str
  6.   else init $ unlines $ formatM n $ wordsWithSpaces str
  7.  
  8. formatM :: Int -> [String] -> [String]
  9. formatM _ [] = []
  10. formatM x y = [removeLastSpace $ concat $ parsed] ++ formatM x (dropS (length parsed) y)
  11.     where parsed = parseW x y
  12.    
  13. removeLastSpace :: String -> String
  14. removeLastSpace x = if isSpace $ last x then init x else x
  15.  
  16. dropS :: Int -> [String] -> [String]
  17. dropS x y = if firstElementIsSpace dropped then tail dropped
  18.             else dropped
  19.             where dropped = drop x y
  20.  
  21. firstElementIsSpace :: [String] -> Bool
  22. firstElementIsSpace x = if null $ take 1 x then False
  23.                         else isSpace $ head $ head $ take 1 x
  24.  
  25. parseW :: Int -> [String] -> [String]
  26. parseW x y = parse 0 x y
  27.  
  28. parse :: Int -> Int -> [String] -> [String]
  29. parse _ _ [] = []
  30. parse x y (a:ax) | len < y = [a] ++ parse len y ax
  31.                   | len == y = if isSpace $ head a then [] else [a]
  32.                   | len > y = []
  33.                   where len = (+x) $ length a
  34.  
  35. wordsWithSpaces :: String -> [String]
  36. wordsWithSpaces = addSpace . words
  37.  
  38. addSpace :: [String] -> [String]
  39. addSpace [] = []
  40. addSpace (a:[]) = [a]
  41. addSpace (a:ax) = [a] ++ [" "] ++ addSpace ax
Advertisement
Add Comment
Please, Sign In to add comment