Skip to content

Instantly share code, notes, and snippets.

@tpolecat
Last active December 20, 2015 01:09
Show Gist options
  • Save tpolecat/6046897 to your computer and use it in GitHub Desktop.
Save tpolecat/6046897 to your computer and use it in GitHub Desktop.
import scala.annotation.tailrec
object Crap extends App {
val BASE = 16
val DIGITS = "0123456789ABCDEF"
// Original
def encode0(number: BigInt): String = {
require(number > 0, "number must not be negative")
val result = new StringBuilder()
var num = number
while (num > 0) {
val (value, rem) = num /% BASE
num = value
result.insert(0, DIGITS.charAt(rem.intValue()))
}
if (result.isEmpty) DIGITS.substring(0, 1) else result.toString()
}
// With direct tail recursion
def encode1(num: BigInt): String = {
@tailrec
def helper(num: BigInt, acc: String): String =
if (num <= 0) acc
else {
val (value, rem) = num /% BASE
helper(value, DIGITS(rem.intValue) + acc)
}
require(num > 0, "number must not be negative")
if (num == 0) DIGITS.substring(0, 1)
else helper(num, "")
}
// With unfold
def unfold[A, B](a: A)(f: A => Option[(A, B)]): Stream[B] =
f(a).map { case (a, b) => b #:: unfold(a)(f) }.getOrElse(Stream.empty)
def encode2(num: BigInt): String = {
require(num > 0, "number must not be negative")
if (num == 0) DIGITS.substring(0, 1)
else unfold(num) { n =>
if (n <= 0) None
else Some {
val (value, rem) = n /% BASE
(value, DIGITS(rem.intValue))
}
}.reverse.mkString
}
println(encode0(123456789))
println(encode1(123456789))
println(encode2(123456789))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment