Reputation: 4660
I'm studying the scala red book published by Manning
The List implementation is a case class:
case class Cons[+A](head: A, tail: List[A]) extends List[A]
foldRight is defined as:
def foldRight[A, B](as: List[A], z: B)(f: (A, B) => B): B
and implemented as
def foldRight[A, B](as: List[A], z: B)(f: (A, B) => B): B = { // Utility functions
as match {
case Nil => z
case Cons(h, t) => f(h, foldRight(t, z)(f))
}
}
To append one List to another, my solution was:
def append[A](l1: List[A], l2: List[A]): List[A]
= foldRight(l1, l2)((l1head,l2)=>Cons(l1head, l2))
the answer key, however, shows the following code:
def append[A](l1: List[A], l2: List[A]): List[A] = foldRight(l1, l2)(Cons(_, _))
Question:
How does (Cons(_, _))
conform to the method signature of f: (A, B) => B
Upvotes: 0
Views: 686
Reputation: 51271
Both append()
examples are exactly the same. The 1st underscore is shorthand for "the 1st passed-in parameter" and the 2nd underscore is shorthand for "the 2nd passed-in parameter." It's just a handy way of referencing them, and passing them on to the Cons
constructor, without the bother of giving each a name.
See also the various answers to this question.
Upvotes: 3