Reputation: 1428
In the following code from "functional-programming-in-scala, what is _
mean here? I think it represent the result of sequence(t), but when I replaced it with sequence(t), it gives me an compile error. Why is that? What can I do to make this _ explicit?
Edit: I'm confused that whether this _
should be expand into result of sequence(t), list all use case for underscore here doesn't help here, I already reviewed it.
@ def sequence[A](a: List[Option[A]]): Option[List[A]] =
a match {
case Nil => Some(Nil)
case h :: t => h flatMap (hh => sequence(t) map (hh :: _))
}
defined function sequence
@
@ sequence(List(Some(1), Some(2))
)
res1: Option[List[Int]] = Some(List(1, 2))
Replace _
with sequence(t)
def sequence[A](a: List[Option[A]]): Option[List[A]] =
a match {
case Nil => Some(Nil)
case h :: t => h flatMap (hh => sequence(t) map (hh :: sequence(t)))
}
cmd4.sc:4: value :: is not a member of Option[List[A]]
case h :: t => h flatMap (hh => sequence(t) map (hh :: sequence(t)))
^
Compilation Failed
Upvotes: 0
Views: 97
Reputation: 44918
In every context, hh :: _
is simply a shortcut for _.::(hh)
, which in turn is a shortcut for x => x.::(h)
, or x => hh :: x
. The type of the argument in this case is List[A]
(because it's a list of A
s inside an Option
). Therefore, your code does the same as the following code:
def sequence[A](a: List[Option[A]]): Option[List[A]] =
a match {
case Nil => Some(Nil)
case h :: t => h flatMap (hh => sequence(t) map ((xs: List[A]) => hh :: xs))
}
Whether it's used inside flatMap
or somewhere else, is completely irrelevant.
Upvotes: 2