同构列表
假设单一类型非常简单
val g1: Int => Option[Int] = x => if (x % 2 == 1) None else Some(x / 2)
val g2: Int => Option[Int] = x => Some(x * 3 + 1)
val g3: Int => Option[Int] = x => if (x >= 4) Some(x - 4) else None
你可以定义
def bind[T]: (Option[T], T => Option[T]) => Option[T] = _ flatMap _
def chain[T](x: T, fs: List[T => Option[T]]) = fs.scanLeft(Some(x): Option[T])(bind)
现在
chain(4, g1 :: g2 :: g3 :: Nil)
将会
列表(一些(4),一些(2),一些(7),一些(3))
保留所有中间值。
异构列表
但是如果涉及到多种类型我们可以吗?
幸运的是,有一个名为 Heterogenous List 的特殊结构的 shapeless 库可以处理类似列表的多类型值序列。
假设我们有
import scala.util.Try
val f1: Int => Option[String] = x => Some(x.toString)
val f2: String => Option[Int] = x => Try(x.toInt).toOption
val f3: Int => Option[Int] = x => if (x % 2 == 1) None else Some(x / 2)
让我们定义以前函数的异构类似物:
import shapeless._
import ops.hlist.LeftScanner._
import shapeless.ops.hlist._
object hBind extends Poly2 {
implicit def bind[T, G] = at[T => Option[G], Option[T]]((f, o) => o flatMap f)
}
def hChain[Z, L <: HList](z: Z, fs: L)
(implicit lScan: LeftScanner[L, Option[Z], hBind.type]) =
lScan(fs, Some(z))
现在
hChain(4, f1 :: f2 :: f3 :: HNil)
评估为
Some(4) :: Some("4") :: Some(4) :: Some(2) :: HNil
类转换器
现在,如果您敦促将结果保存在某个类中,例如
case class Result(init: Option[Int],
x1: Option[String],
x2: Option[Int],
x3: Option[Int])
你可以很容易地使用它Generic representation
只要确保自己这样做
Generic[Result].from(hChain(4, f1 :: f2 :: f3 :: HNil)) ==
Result(Some(4),Some("4"),Some(4),Some(2))