Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scala calculate the amount a certain object appears in a sequence

I am new to Scala and i am trying to create a function that calculates the amount a certain object appears in a sequence. So in this case we have a sequence with 1 Hippo and 3 Tigers in it. I want the amount of Tigers in the sequence. So the outcome of the function amountOfTigers should be an integer: 3. I want to make use of pattern matching and recursion to solve this. But i dont really know how to do this.

sealed trait Animal

case class Hippo(name: String, age: Int) extends Animal
case class Tiger(name: String, age: Int) extends Animal
def amountOfTigers(animals: Seq[Animal]): Int = animals match {
    case head +: tail => if (head.isInstanceOf[Tiger]) println(head); amountOfTigers(tail)
  }
val data = Seq[Animal](
    Hippo("Mino", 4),
    Tiger("Justin", 1),
    Tiger("Jason", 20),
    Tiger("Sloop", 10)
  )
  amountOfTigers(data)

println is used for testing purposes.
The output i am getting right now is:
Tiger(Justin,1)
Tiger(Jason,20)
Tiger(Sloop,10)

I want as a result the amount of Tigers in a sequence. So in this case its 3.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is an example:

sealed trait Animal

case class Hippo(name: String, age: Int) extends Animal
case class Tiger(name: String, age: Int) extends Animal

def amountOfTigers(animals: Seq[Animal]): Int = animals match {
  case Seq() => 0
  case Tiger(_, _) +: tail => amountOfTigers(tail) + 1
  case head +: tail => amountOfTigers(tail)
}

val data = Seq[Animal](
    Hippo("Mino", 4),
    Tiger("Justin", 1),
    Tiger("Jason", 20),
    Tiger("Sloop", 10)
  )
  
print(amountOfTigers(data))

Things you might want to check out:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading