Search code examples
scalarecursionpattern-matchingsequencetail-recursion

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.


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: