flatten2.
trait Monad[F[_]] {
def flatMap2[A, B](fa: F[A])(f: A => F[B]): F[B]
def flatten2[A](f: F[F[A]]): F[A] =
flatMap2(f)(fa => fa)
}
object Monad {
def apply[F[_]](implicit instance: Monad[F]): Monad[F] = instance
implicit val optionMonad: Monad[Option] = new Monad[Option] {
override def flatMap2[A, B](fa: Option[A])(f: A => Option[B]): Option[B] = fa.flatMap(f)
}
implicit val listMonad: Monad[List] = new Monad[List] {
override def flatMap2[A, B](fa: List[A])(f: A => List[B]): List[B] = fa.flatMap(f)
}
implicit val setMonad: Monad[Set] = new Monad[Set] {
override def flatMap2[A, B](fa: Set[A])(f: A => Set[B]): Set[B] = fa.flatMap(f)
}
implicit class MonadOps[F[_]: Monad](f: F[_]){
def flatten2[A](implicit f: F[F[A]]): F[A] = Monad[F].flatten2(f)
}
}
}
Но в при сиользовании метод flatten2 не подцепляется
val oo = Some(Some("foo"))
val o = oo.flatten2
println(o)
Пишет что value flatten2 is not a member of Some[Some[String]] val o = oo.flatten2. Ошибка где-то в implicit class?
val oo = Some(Some("foo")) val o = Monad[Option].flatten2(oo) println(o)
там тип выводится Some скорее всего
val oo = Some("foo") val o = oo.flatten2
trait Monad[F[_]] { def flatMap2[A, B](fa: F[A])(f: A => F[B]): F[B] def flatten2[A](fa: F[F[A]]): F[A] = flatMap2(fa)(identity) } object Monad { def apply[F[_]](implicit instance: Monad[F]): Monad[F] = instance implicit val monadOption = new Monad[Option] { override def flatMap2[A, B](fa: Option[A])(f: A => Option[B]): Option[B] = fa.flatMap(f) } implicit class MonadOps[A, F[_]: Monad](self: F[A]) { def flatMap2[B](f: A => F[B]): F[B] = Monad[F].flatMap2[A, B](self)(f) } implicit class MonadFlat[A, F[_]: Monad](self: F[F[A]]) { def flatten2 = Monad[F].flatten2(self) } } object Main { import Monad._ def main(args: Array[String]): Unit = { val o1: Option[Int] = Some(42) val o2 = o1.flatMap2(x => Some(x + 10)) val o3: Option[Option[Int]] = Some(Some(42)) val o4 = o3.flatten2 println(o4) } }
а flatMap2 для чего имплисить?
val o1: Option[Int] = Some(42) val o2 = o1.flatMap2(x => Some(x + 10)) val o2_2 = Monad[Option].flatMap2(o1)(x => Some(x + 10))
почему здесь не работает имеете в виду?
Обсуждают сегодня