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))
}
@suhailshergill
Copy link

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 the Boolean controls how i operate in relaxed type (Int). subtle difference

def isEven: Int => Boolean
def isPositive: Int => Boolean
def list: Seq[Int]
def incrementIfTrue: Boolean => Int => Int = (b: Boolean) => (n: Int) => if b (n+1) else n
def processing: Seq[Int] => [(Boolean, Boolean)] => Seq[(Int, Int)] = (xs: Seq[Int]) => {
xs.
  map(x => (isEven(x), isPositive(x))).
  foldLeft((0, 0)) {
    case ((numEven, numPos), (isEven, isPos)) => {
      (incrementIfTrue(isEven)(numEven), incrementIfTrue(isPos)(numPos))
    }
  }
}

@ldacosta
Copy link
Author

+1

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