嗨,我正试图只返回true或false,但我缺少某些东西
def filterOut[T](p: T => Boolean, as: List[T]): List[T] = {
as.foldLeft(List[T]())((out, x) =>
if (p(x)) {x::out} else {out}
)}
其中p是谓词。你能帮我吗?
您是否需要使用foldLeft()
?
def atLeastOne[T](p: T => Boolean, as: Seq[T]): Boolean =
as.foldLeft(false)(_ || p(_))
或者您被允许更直接吗?
def atLeastOne[T](p: T => Boolean, as: Seq[T]): Boolean =
as exists p
测试:
atLeastOne((x:Int) => x > 57, List(3,11,71,43,5)) //res0: Boolean = true
atLeastOne[Char]('w'.==, "abcdef") //res1: Boolean = false
atLeastOne[String](_.isEmpty, "this-and--that".split("-")) //res2: Boolean = true
atLeastOne[Float](_ < 1F, Vector()) //res3: Boolean = false