Skip to content

Instantly share code, notes, and snippets.

@privateblue
Created November 7, 2014 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save privateblue/59e4be3aed87e3a37530 to your computer and use it in GitHub Desktop.
Save privateblue/59e4be3aed87e3a37530 to your computer and use it in GitHub Desktop.
object chapter2 {
def simplefib(n: Int): Int =
if (n <= 1) n
else simplefib(n - 1) + simplefib(n - 2)
def fib(n: Int): Int = {
@annotation.tailrec
def loop(i: Int, acc: Int, x: Int): Int =
if (i <= 0) acc
else loop(i - 1, x, acc + x)
loop(n, 0, 1)
}
def isSorted[A](as: Array[A], ordered: (A,A) => Boolean): Boolean = {
@annotation.tailrec
def loop(i: Int, acc: Boolean): Boolean =
if (i < as.size - 1 && acc) loop(i + 1, ordered(as(i), as(i + 1)))
else acc
loop(0, true)
}
def curry[A,B,C](f: (A, B) => C): A => (B => C) = a => b => f(a, b)
def uncurry[A,B,C](f: A => B => C): (A, B) => C = (a, b) => f(a)(b)
def compose[A,B,C](f: B => C, g: A => B): A => C = a => f(g(a))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment