如何为 Option[List[_]] n Scala 定义 <*>

How to define <*> for Option[List[_]] n Scala

这是我之前 的后续内容,其中包含一个在 Internet 上找到的示例。

假设我定义一个类型类Applicative如下:

trait Functor[T[_]]{
  def map[A,B](f:A=>B, ta:T[A]):T[B]
}

trait Applicative[T[_]] extends Functor[T] {
  def unit[A](a:A):T[A]
  def ap[A,B](tf:T[A=>B], ta:T[A]):T[B]
}

我可以为 List

定义一个 Applicative 的实例
object AppList extends Applicative[List] {
  def map[A,B](f:A=>B, as:List[A]) = as.map(f)
  def unit[A](a: A) = List(a)
  def ap[A,B](fs:List[A=>B], as:List[A]) = for(f <- fs; a <- as) yield f(a)
}

为了方便我可以定义一个implicit conversion来添加一个方法<*>List[A=>B]

implicit def toApplicative[A, B](fs: List[A=>B]) = new {
  def <*>(as: List[A]) = AppList.ap(fs, as)
}

现在我可以做一件很酷的事了!
压缩两个列表 List[String] 并将 f2 应用于 applicative 样式

中的每一对
val f2: (String, String) => String = {(first, last) => s"$first $last"}
val firsts = List("a", "b", "c")
val lasts  = List("x", "y", "z")

scala> AppList.unit(f2.curried) <*> firsts <*> lasts
res31: List[String] = List(a x, a y, a z, b x, b y, b z, c x, c y, c z)

到目前为止,还不错,但现在我有:

val firstsOpt = Some(firsts)
val lastsOpt  = Some(lasts) 

我想压缩 firstslasts,应用 f2,并以 applicative 样式获得 Option[List[String]]。换句话说,我需要 <*> 来获得 Option[List[_]]。我该怎么做?

首先,您需要一个适用于 Option:

的实例
implicit object AppOption extends Applicative[Option] {
  def map[A, B](f: A => B, o: Option[A]) = o.map(f)
  def unit[A](a: A): Option[A] = Some(a)
  def ap[A, B](of: Option[A => B], oa: Option[A]) = of match {
    case Some(f) => oa.map(f)
    case None => None
  }
}

那么你也可以创建一个applicative instance,用于组合两个applicatives(注意,基于Haskell version):

class AppComp[F[_], G[_]](fa: Applicative[F], ga: Applicative[G]) extends Applicative[({ type f[A] = F[G[A]]})#f] {
  def map[A, B](f: A => B, a: F[G[A]]): F[G[B]] = fa.map((g: G[A]) => ga.map(f, g), a)
  def unit[A](a: A) = fa.unit(ga.unit(a))
  def ap[A, B](f: F[G[A => B]], a: F[G[A]]): F[G[B]] = {
    val liftg: G[A => B] => (G[A] => G[B]) = gf => (gx => ga.ap(gf, gx))
    val ffg: F[G[A] => G[B]] = fa.map(liftg, f)
    fa.ap(ffg, a)
  }
}

implicit def toComp[F[_], G[_]](implicit fa: Applicative[F], ga: Applicative[G]) = new AppComp[F, G](fa, ga)

你终于可以做到了:

val ola = toComp[Option, List]
ola.ap(ola.ap(ola.unit(f2.curried), firstsOpt), lastsOpt)

您可能还可以通过概括 <*> 以适用于任何应用程序来消除一些噪音。