Skip to content

Instantly share code, notes, and snippets.

@rburgosnavas
Created August 7, 2013 00:12
Show Gist options
  • Save rburgosnavas/f355b989979436d90e96 to your computer and use it in GitHub Desktop.
Save rburgosnavas/f355b989979436d90e96 to your computer and use it in GitHub Desktop.
This is to practice tail recursion by creating a method that splits text after 80 characters long and adds the next line over. split80(...) works but it is not tail recursive. newSplit80(...) attempts that.
/**
* Recursive split text to lines of 80 characters
*/
def split80(text: String): String = {
if (text.length <= 80) {
text
} else {
text.substring(0, 80) + "\n" + split80(text.substring(80))
}
}
/**
* Recursive split text to lines of 80 characters
*/
def newSplit80(text: String): String = {
def loop(acc: String, line: String): String = {
if (acc.length <= 80)
acc
else
loop(acc.substring(80), acc + line)
}
loop(text, "\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment