【发布时间】:2021-01-17 19:24:42
【问题描述】:
我有一个男性和女性居民的列表要迭代。
如何在列表模式匹配中添加基于性别的过滤? (这样countOldManFloor 只有在居民性别为Male 时才会返回1,因此countOldManFloor(inhabitantsFemale) 将返回0)
import scala.annotation.tailrec
trait Gender
case object Female extends Gender
case object Male extends Gender
case class Inhabitant(age: Int= 50, gender: Gender)
val olderThen = 30
val inhabitantsBoth: List[Inhabitant] = List(Inhabitant(gender=Male), Inhabitant(gender=Female))
val inhabitantsFemale: List[Inhabitant] = List(Inhabitant(gender=Female), Inhabitant(gender=Female))
val inhabitantsMale: List[Inhabitant] = List(Inhabitant(gender=Male), Inhabitant(gender=Male))
@tailrec
def countOldManFloor(inhabitants: List[Inhabitant]): Int = inhabitants match {
case inhabitant :: inhabitants if inhabitant.age > olderThen => 1
case inhabitant :: inhabitants => countOldManFloor(inhabitants)
case Nil => 0
}
println(countOldManFloor(inhabitantsBoth))
println(countOldManFloor(inhabitantsMale))
println(countOldManFloor(inhabitantsFemale))
我尝试了case inhabitant: Male :: inhabitants if inhabitant.age > olderThen => 1 和= inhabitants.filter() match {},但没有成功
【问题讨论】:
-
嗨@techkuz,您想通过
Gender和age进行检查,还是两者兼而有之?我不明白。 -
嗨@Chema。两者,我只需要计算年龄过滤的男性
-
嗨@techkuz,如果我没记错的话,结果将是30岁以上的男性。
标签: scala functional-programming pattern-matching tail-recursion