Advertisement
sa2304

Wrap text in Haskell

Nov 8th, 2020
2,779
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. wrapText text width =
  2.   unlines $ reverse $ makeReversedParagraph(words text) width [""]
  3.  
  4. appendWordToLine [] word = word
  5. appendWordToLine line word = line ++ " " ++ word
  6.  
  7. appendWordToReversedParagraph :: [String] -> String -> Int -> [String]
  8. appendWordToReversedParagraph (x:xs) word width
  9.   | length word <= width =
  10.     if length (x ++ word) + 1 <= width
  11.     then [appendWordToLine x word] ++ xs
  12.     else [word] ++ x:xs
  13.   | otherwise = [ drop width word ] ++ [ take width word ] ++ x:xs
  14.  
  15. makeReversedParagraph :: [String] -> Int -> [String] -> [String]
  16. makeReversedParagraph [] _ par = par
  17. makeReversedParagraph (x:xs) width par = makeReversedParagraph xs width (appendWordToReversedParagraph par x width)
  18.  
  19. main = do
  20.   let text = "Lorem ipsum  dolor sit amet, consectetur        adipiscing elit, sed do eiusmod tempoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur."
  21.   putStr(wrapText text 40)
  22.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement