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

2024-02-20

这是我之前的后续question https://stackoverflow.com/questions/28850636/example-of-applicative-composition-in-scala在互联网上找到一个例子。

假设我定义了一个类型类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]
}

我可以定义一个实例Applicative for List

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添加一个方法<*> to List[A=>B]

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

现在我可以做一件很酷的事情了!
压缩两个列表List[String]并申请f2到每一对应用性的 style

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) 

我想要拉链firsts and lasts, apply f2,并得到Option[List[String]] in 应用性的风格。换句话说我需要<*> for 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
  }
}

然后你还可以为两个applicatives的组合创建一个applicative实例(注意,基于哈斯克尔版本 https://hackage.haskell.org/package/transformers-0.4.2.0/docs/src/Data-Functor-Compose.html#Compose):

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)

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Scala 中为 Option[List[_]] 定义 <*> 的相关文章

随机推荐