Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of Ints in Scala list using a fold

Tags:

scala

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?

like image 546
fia928 Avatar asked Dec 15 '22 15:12

fia928


2 Answers

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
  })
like image 58
Carsten Avatar answered Jan 07 '23 08:01

Carsten


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
like image 43
Brian Avatar answered Jan 07 '23 07:01

Brian