2
votes

I am learning Scala Higher Order Functions. I am studying an example that is a class; there is one method that receives a function and a value parameter and returns a value. The function is p: Tweet => Boolean and the method implementation is further below. I want to know where is the implementation of the p function.

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)
    }                    
}
1
I understand it might be more disturbing when the parameter is a function, but your question is in fact exactly the same as "what is the value of the acc parameter?". It is whatever is passed as acc when filterAcc is called. Same for p.Didier Dupont

1 Answers

2
votes

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

If you go further down in the class definition, you'll see one of the implementations of p in union

def union(that: TweetSet): TweetSet = {
  this.filterAcc(elem => true, that)
}

With Higher Order Functions, the caller of the method is the one in charge of providing an implementation of the function that he wishes to run. You can take a look at common use cases such as map, flatMap, filter, etc on Scalas collection library.