Last active
August 29, 2015 14:05
-
-
Save ldacosta/3f2bba90aba8bf0526ee to your computer and use it in GitHub Desktop.
Counting Booleans
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
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) |
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
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)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
whether to do things in one pass or many is an orthogonal point. below, i do things in one pass while still avoiding converting a specific type (
Boolean
) to a more relaxed one (Int
). instead theBoolean
controls how i operate in relaxed type (Int
). subtle difference