fia928
fia928

Reputation: 143

Count number of Ints in Scala list using a fold

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

Answers (2)

Carsten
Carsten

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

Brian
Brian

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

Related Questions