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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.