Skip to content

Instantly share code, notes, and snippets.

@rkrzewski
Last active August 29, 2015 13:56
Show Gist options
  • Save rkrzewski/8828958 to your computer and use it in GitHub Desktop.
Save rkrzewski/8828958 to your computer and use it in GitHub Desktop.
def fib(a: Int, b: Int): Stream[Int] = a #:: fib(b, a + b)
fib(1, 1).take(10).toList // == List(1, 1, 2, 3, 5, 8, 13, 21, 34, 55)
fib(1, 1).takeWhile(_ < 4000000).filter(_ % 2 == 0).sum // == 4613732
// --------------------------------------------------------------
def euler1(l: Int) =
(1 until l).toStream.filter(x => x % 3 == 0 || x % 5 == 0).sum
def reverse1[T](ts: Seq[T]): Seq[T] =
ts.foldLeft(Seq.empty[T]) { (a, e) => e +: a }
def reverse2[T](ts: Seq[T]): Seq[T] = ts match {
case Seq() => ts
case h +: t => reverse2(t) :+ h
}
def reverse[T](ts: Seq[T]): Seq[T] = {
@tailrec
def go(ts: Seq[T], acc: Seq[T]): Seq[T] = ts match {
case Seq() => acc
case h +: t => go(t, h +: acc)
}
go(ts, Seq())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment