Skip to content

Instantly share code, notes, and snippets.

@ybiquitous
Created June 3, 2012 10:25
Show Gist options
  • Save ybiquitous/2862947 to your computer and use it in GitHub Desktop.
Save ybiquitous/2862947 to your computer and use it in GitHub Desktop.
Scala `mkString` tail-recursion version
import scala.annotation.tailrec
import scala.collection.mutable.StringBuilder
def mkStr(elems: Seq[_], sep: String = ""): String = {
/* invoke java.lang.StackOverflowError
elems match {
case Seq() => ""
case Seq(head) => head.toString
case _ => elems.head + sep + mkStr(elems.tail, sep)
}
*/
@tailrec
def worker(buf: StringBuilder, seq: Seq[_]): StringBuilder = seq match {
case Seq() => buf
case Seq(head) => buf.append(head)
case _ => worker(buf.append(seq.head).append(sep), seq.tail)
}
worker(new StringBuilder, elems).toString
}
// test
assert{ mkStr(1 to 0, ", ") == ("") }
assert{ mkStr(1 to 1, ", ") == ("1") }
assert{ mkStr(1 to 2, ", ") == ("1, 2") }
assert{ mkStr(1 to 3, ", ") == ("1, 2, 3") }
// benchmark
val fixture = (0 to 1000000)
val sep = ", "
val count = 10
val mkstring = new scala.testing.Benchmark {
def run = fixture.mkString(sep)
}.runBenchmark(count)
println("standard `mkString` => " + mkstring)
val mkstr = new scala.testing.Benchmark {
def run = mkStr(fixture, sep)
}.runBenchmark(count)
println("tail recursion `mkString` => " + mkstr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment