在Scala中的函数式编程一书中,有一个问题要求将选项列表转换为列表选项。函数签名如下:
def sequence[A](a:List[Option[A]]):Option[List[A]]
在本书的网站上,这个功能是这样实现的:
def sequence[A](a:List[Option[A]]):Option[List[A]] = a match {
case Nil => Some(Nil)
case h::t => h flatMap (r => sequence(t) map (h::_))
}
我对这h flatMap (r => sequence(t) map (h::_))部分有点困惑。如果我分解它,它会如下所示:
h 是 类型Option[A]。在 h 上执行 flatMap 将返回 anOption[B]但它需要一个函数 f 作为参数,该函数将 A 作为参数并返回 an Option[B],现在在上面的示例中,sequence(t) map (h :: _)将返回Option[List[A]]与函数的返回类型一致的 an。
可以使用 map 代替 flatMap 来执行从List[Option[A]]to的转换Option[List[A]]吗?此外,提供的解决方案似乎不是尾递归的。可以做尾递归吗?