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?
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
})
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With