Skip to content

Instantly share code, notes, and snippets.

@ldacosta
Last active August 29, 2015 14:05
Show Gist options
  • Save ldacosta/3f2bba90aba8bf0526ee to your computer and use it in GitHub Desktop.
Save ldacosta/3f2bba90aba8bf0526ee to your computer and use it in GitHub Desktop.
Counting Booleans
def isEven(x:Int) = (x % 2 == 0)
def isPositive(x: Int) = (x > 0)
def aList = List(1,2,-2,34,57, -91, -90)
// in this case I go from [Int] => [Bool] => Int. 2 times, because I have 2 functions.
val (numEven, numPos) = (aList.map(isEven).filter(_ == true).length, aList.map(isPositive).filter(_ == true).length)
def isEven(x:Int) = (x % 2 == 0)
def isPositive(x: Int) = (x > 0)
def aList = List(1,2,-2,34,57, -91, -90)
// in this case I go from [Int] => (Int,Int)
val (numEven, numPos) = aList.foldLeft((0,0)) { case ((howManyEven, howManyPos), n) =>
(howManyEven + (if (isEven(n)) 1 else 0), howManyPos + (if (isPositive(n)) 1 else 0))
}
@ldacosta
Copy link
Author

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment