Created
November 14, 2014 21:28
-
-
Save betandr/73f521021e02f0b8669d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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