我有以下應用性的定義和實現:哪裏其他結果
import simulacrum._
@typeclass trait Applicative[F[_]] {
def pure[A](a: A): F[A]
def apply[A, B](fa: F[A])(ff: F[A => B]): F[B]
def map[A,B](fa: F[A])(f: A => B): F[B] =
apply(fa)(pure(f))
}
object Applicative {
implicit val optionApplicative: Applicative[Option] = new Applicative[Option] {
def pure[A](a: A): Option[A] = Some(a)
def apply[A, B](fa: Option[A])(ff: Option[A => B]): Option[B] = (fa, ff) match {
case (None, _) => None
case (Some(_), None) => None
case (Some(a), Some(f)) => Some(f(a))
}
}
implicit val listApplicative: Applicative[List] = new Applicative[List] {
def pure[A](a: A): List[A] = List(a)
def apply[A, B](fa: List[A])(ff: List[A => B]): List[B] =
(fa zip ff).map { case (a, f) => f(a) }
}
}
當我名單上執行地圖:
Applicative[List].map(List(1,2,3))(_ + 1)
我有:
res2: List[Int] = List(2)
但我確實期待List(2,3,4)
。我究竟做錯了什麼?