简体   繁体   English

Scala 计算某个object在一个序列中出现的数量

[英]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.我是 Scala 的新手,我正在尝试创建一个 function 来计算某个 object 在序列中出现的数量。 So in this case we have a sequence with 1 Hippo and 3 Tigers in it.所以在这种情况下,我们有一个包含 1 只河马和 3 只老虎的序列。 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.所以 function amountOfTigers 的结果应该是 integer: 3. 我想利用模式匹配和递归来解决这个问题。 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. println 用于测试目的。 The output i am getting right now is: Tiger(Justin,1) Tiger(Jason,20) Tiger(Sloop,10)我现在收到的 output 是: 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.所以在这种情况下是 3。

If you want to avoid recursion (which I personally suggest in this case - cause it's just an ordinary array of data), I suggest you use a loop, this way:如果你想避免递归(在这种情况下我个人建议 - 因为它只是一个普通的数据数组),我建议你使用循环,这样:

  def amountOfTigers(animals: Seq[Animal]): Int = animals.count(_.isInstanceOf[Tiger])

If you insist using recursion, I suggest using @tailrec as Christian hinted:如果您坚持使用递归,我建议使用@tailrec ,正如 Christian 所暗示的那样:

def amountOfTigersRec(animals: Seq[Animal]): Int = {
    @tailrec
    def rec_fun(tail: Seq[Animal], count: Int): Int = tail match {
      case Tiger(_, _) +: tail => rec_fun(tail, count + 1)
      case _ +: tail => rec_fun(tail, count)
      case Nil => count
    }

    rec_fun(animals, 0)
  }

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:您可能想要查看的内容:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM