Created
August 7, 2013 00:12
-
-
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.
This file contains 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
/** | |
* 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