Skip to content

Instantly share code, notes, and snippets.

@MagnusSmith
Last active December 12, 2015 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MagnusSmith/a5feaf027ef5dd8c9b75 to your computer and use it in GitHub Desktop.
Save MagnusSmith/a5feaf027ef5dd8c9b75 to your computer and use it in GitHub Desktop.
wordwrap in scala
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