Last active
December 12, 2015 12:06
-
-
Save MagnusSmith/a5feaf027ef5dd8c9b75 to your computer and use it in GitHub Desktop.
wordwrap in scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.annotation.tailrec | |
val sentence = "Four score and ten years ago our fathers brought forth upon this " + | |
"continent a new nation conceived in liberty and dedicated to the " + | |
"proposition that all men are created equal" | |
def wrap(source: String, len: Int):String = { | |
val wordChunks = sentence.split(" ").flatMap(x => x.grouped(len)).toList | |
def concatenate(word: String, line: String):(Option[String], String) = { | |
def wrappedLine(): Option[String] = {if ((line.length + word.length) < len) None else Some(line)} | |
def remaining(): String = {if ((line.length + word.length) < len && !line.isEmpty) line + " " + word else word} | |
(wrappedLine, remaining) | |
} | |
@tailrec | |
def loop(words: List[String], partialLine: String, wrappedLines: List[String]): List[String] = { | |
words match { | |
case x :: xs => { | |
val c = concatenate(x, partialLine) | |
loop(xs, c._2, c._1.fold(wrappedLines)(wrappedLine => wrappedLine + "\n" :: wrappedLines)) | |
} | |
case Nil => { | |
(partialLine + "\n") :: wrappedLines | |
} | |
} | |
} | |
loop(wordChunks, "", List()).reverse.mkString | |
} | |
System.out.println(wrap(sentence, 10)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment