Skip to content

Instantly share code, notes, and snippets.

@darionyaphet
Created April 21, 2017 03:41
Show Gist options
  • Save darionyaphet/1fd73d81ec3a02cd7082828757ba53e5 to your computer and use it in GitHub Desktop.
Save darionyaphet/1fd73d81ec3a02cd7082828757ba53e5 to your computer and use it in GitHub Desktop.
TailCalls
package org.darion.yaphet.scala.examples.other
import scala.util.control.TailCalls._
import scala.annotation._
object Sum extends App {
def evenLength(xs: Seq[Int]): TailRec[Boolean] =
if (xs.isEmpty) done(true) else tailcall(oddLength(xs.tail))
def oddLength(xs: Seq[Int]): TailRec[Boolean] =
if (xs.isEmpty) done(false) else tailcall(evenLength(xs.tail))
println(evenLength(1 to 1000000).result)
def sum1(xs: Seq[Int], partial: BigInt): TailRec[BigInt] =
if (xs.isEmpty) done(partial) else tailcall(sum1(xs.tail, xs.head + partial))
println(sum1(1 to 1000000, 0).result)
@tailrec def sum2(xs: Seq[Int], partial: BigInt): BigInt =
if (xs.isEmpty) partial else sum2(xs.tail, xs.head + partial)
println(sum2(1 to 1000000, 0))
def sum3(xs: Seq[Int]): BigInt =
if (xs.isEmpty) 0 else xs.head + sum3(xs.tail)
try {
println(sum3(1 to 1000000))
} catch {
case _ => println("wrong")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment