您需要做的是对dropWhile 进行修改,我将其称为filterWhile。
利用 Collection API 的一个简单解决方案如下:
def filterWhile[A](
list: List[A]
)(filterP: A => Boolean, whileP: A => Boolean): List[A] = {
val (toFilter, unfiltered) = list.span(whileP)
toFilter.filter(filterP) ++ unfiltered
}
您可以使用此代码 here on Scastie,并进行一些测试以验证其是否按预期工作,如下所示:
def test[A](
input: List[A],
expected: List[A]
)(filterP: A => Boolean, whileP: A => Boolean): Unit =
assert(
filterWhile(input)(filterP, whileP) == expected,
s"input: $input, expected: $expected, got: ${filterWhile(input)(filterP, whileP)}"
)
test(
input = List(0, 0, 0, 0, 0, 3, '.', 5, 0, 2, 5),
expected = List(3, '.', 5, 0, 2, 5)
)(filterP = _ != 0, whileP = _ != 3)
test(
input = List(0, 0, 0, 1, 0, 3, '.', 5, 0, 2, 5),
expected = List(1, 3, '.', 5, 0, 2, 5)
)(filterP = _ != 0, whileP = _ != 3)
test(
input = List(1, 2, 3, 4),
expected = List(1, 2, 3, 4)
)(filterP = _ < 5, whileP = _ < 5)
在您的情况下,您所要做的就是按如下方式调用该函数:
filterWhile(tempList)(_ != 0, _ != 3)
第一个谓词说明如何过滤,第二个谓词定义“while”子句。我选择将谓词顺序与函数名称对齐(它首先说“过滤器”,然后是“while”),但可以根据您的喜好随意调整。无论如何,在这里使用命名参数可能是一件好事。