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

[亡魂溺海] 提交于 2019-12-10 16:06:57

问题


This is a followup to my previous question with an example found on the Internet.

Suppose I define a typeclass Applicative as follows:

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]
}

I can define an instance of 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)
}

For convenience I can define an implicit conversion to add a method <*> to List[A=>B]

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

Now I can do a cool thing !
zip two lists List[String] and apply f2 to every pair in applicative 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)

So far, so good but now I have:

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

I would like to zip firsts and lasts, apply f2, and get Option[List[String]] in applicative style. In other words I need <*> for Option[List[_]]. How can I do it ?


回答1:


Firstly, you need an instance of applicative for 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
  }
}

Then you can also create an applicative instance for the composition of two applicatives (note, based on the 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)

Finally you can now do:

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

You could probably also remove some of the noise by generalising <*> to work for any applicative.



来源:https://stackoverflow.com/questions/28875350/how-to-define-for-optionlist-n-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!