如何在Scala上写有限制的过滤器?

时间:2019-01-24 05:08:08

标签: scala filter functional-programming

让我有一些结构的大数组(在下面的示例中,为简单起见,Int)并想过滤该数组并采用第n个元素。我该怎么办?

示例:

val outerVar = 22

def filterFunction(a: Int): Boolean = {
  if (true/* some condition into this */) return false
  if (a > 12) return true
  if (a > 750) return false
  if (a == 42) return true
  if (a == outerVar) return true
  // etc conditions that can use context of outer space
  false
}

val n = 42
val bigArray = Array(1, 2, 3, 4, 5)
val result = bigArray.filter(element => {
  filterFunction(element)
})
//.limit(n) (something like)
// how to stop filling result after it will contain n elements?

1 个答案:

答案 0 :(得分:0)

我相信,您的谓词filterFunction不会继续工作,因为它总是返回false

让我们考虑一个玩具示例,其中有一个Array[Int],我们需要在其上加上谓词filter来使用filterFunction,以便一旦n元素被使用后就停止求值。提取:

scala> :paste
// Entering paste mode (ctrl-D to finish)

val array = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val filterFunction = (a: Int) => a > 5
val getLazy = (n: Int) => array.view.filter(filterFunction).take(n).toArray

getLazy(2)

// Exiting paste mode, now interpreting.

array: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
filterFunction: Int => Boolean = <function1>
getLazy: Int => Array[Int] = <function1>
res0: Array[Int] = Array(6, 7)

array.view.filter(filterFunction).take(n)变为惰性表达式(不会立即进行评估),实际上toArray将运行计算。