Scala 高阶函数详解

Scala Higher order functions in details

我正在学习 Scala 高阶函数。我正在研究an example那是一个class;有一种方法接收函数和值参数以及 returns 值。函数是p: Tweet => Boolean,方法实现在下面。我想知道p函数的实现在哪里。

class NonEmpty(elem: Tweet, left: TweetSet, right: TweetSet) extends TweetSet {
  def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = {
    if (p(elem)) {
      left.filterAcc(p, acc.incl(elem))
      right.filterAcc(p, acc.incl(elem))  
    } else {
        left.filterAcc(p, acc)
        right.filterAcc(p, acc)
    }                    
}

I wonder to know where is the implementation of the p function

如果在 class 定义中进一步向下,您将在 union

中看到 p 的实现之一
def union(that: TweetSet): TweetSet = {
  this.filterAcc(elem => true, that)
}

对于高阶函数,方法的调用者是负责提供他希望 运行 的函数实现的人。您可以查看 Scalas 集合库上的常见用例,例如 mapflatMapfilter 等。