Skip to content

Instantly share code, notes, and snippets.

@jmora
Last active August 29, 2015 14:21
Show Gist options
  • Save jmora/a26695d2f5f0e3959f8f to your computer and use it in GitHub Desktop.
Save jmora/a26695d2f5f0e3959f8f to your computer and use it in GitHub Desktop.
README

In reference to a post comparing programming languages.

I did two versions, the first one is closer to the original, the second one is more efficient and nicer IMHO.

I have been thinking about choosing "the best programming language" for a while, for a number of reasons, including long term DRY.

// Idiomatic version
object HofstadterQseqIdiomatic extends App {
def q(n: Int): Int =
if (n <= 2) 1
else q(n - q(n - 1)) + q(n - q(n - 2))
def linePrint(index: Int, value: Int) = println(s"Q($index) = $value")
(1 to 10) map { i => (i, q(i)) } foreach (linePrint _).tupled
linePrint(1000, q(1000))
}
// Idiomatic and efficient version
object HofstadterQseqEfficient extends App {
val q: Stream[Int] = 1 #:: 1 #:: 1 #:: (3 to Int.MaxValue).iterator.map { n =>
q(n - q(n - 1)) + q(n - q(n - 2))
}.toStream
(1 to 10) foreach { i => println(s"Q($i) = ${q(i)}") }
println(s"Q(1000) = ${q(1000)}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment