Skip to content

Instantly share code, notes, and snippets.

@betandr
Created November 14, 2014 21:28
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 betandr/73f521021e02f0b8669d to your computer and use it in GitHub Desktop.
Save betandr/73f521021e02f0b8669d to your computer and use it in GitHub Desktop.
// Nth Item
import scala.annotation.tailrec
def find(list: List[Int], item: Int) : Int = {
@tailrec def f(l: List[Int], i: Int, acc: Int): Int =
if(l.head == i) acc
else f(l.tail, i, acc+1)
f(list, item, 0)
}
val index = find(List(1, 2, 3, 4, 5, 6, 7, 8, 9), 9)
s"The item is at position ${index}"
// Higher-Order Functions
def values = (f: Int => Int, x: Int, y: Int) => for (i <- x to y) yield (i, f(i))
values(x => x*x, -2, 2)
// Composing Predicates
def isEven = (x: Int) => if (x % 2 == 0) true else false
val negate = (f: Int => Boolean) => (x: Int) => !f(x)
val isOdd = negate(isEven)
isEven(2)
isOdd(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment