Reputation: 143
Say I have the following list of type Any:
val list = List("foo", 1, "bar", 2)
I would now like to write a function that counts only the number of Ints in a list using a fold. In the case of the list above, the result should be "2".
I know counting the number of all elements using fold would look something like this:
def count(list: List[Any]): Int =
list.foldLeft(0)((sum,_) => sum + 1)
How can I tweak this to only count occurrences of Int?
Upvotes: 4
Views: 3165
Reputation: 18446
Another version:
list.count(_.isInstanceOf[Int])
And, if you insist on the foldLeft
version, here is one:
def count(list: List[Any]): Int =
list.foldLeft(0)((sum, x) => x match {
case _: Int => sum + 1
case _ => sum
})
Upvotes: 11
Reputation: 20285
Filtering list
by Int
and taking the size
gives you what you want and is fairly straightforward.
scala> list.filter(_.isInstanceOf[Int]).size
res0: Int = 2
Upvotes: 1