Skip to content

Instantly share code, notes, and snippets.

@avivshafir
Last active April 23, 2018 07:01
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 avivshafir/4d1c4fa087c1f10884a69fd0e64cb234 to your computer and use it in GitHub Desktop.
Save avivshafir/4d1c4fa087c1f10884a69fd0e64cb234 to your computer and use it in GitHub Desktop.
fp in scala part 1
def fib(n: Int): Int = {
@annotation.tailrec
def loop(n: Int, prev: Int, cur: Int): Int =
if (n == 0) prev
else loop(n - 1, cur, prev + cur)
loop(n, 0, 1)
}
fib(6)
def isSorted[A](as: Array[A], ordered: (A,A) => Boolean): Boolean = {
def loop(index: Int): Boolean =
if (as.length == index + 1) true
else if (!ordered(as(index + 1), as(index))) false
else loop(index + 1)
loop(0)
}
isSorted(Array(1,3,4, 12, 5), (x: Int, y: Int) => x > y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment