Share
Embed
Scalaで関数型 再入門
よく遭遇する、Scala標準ライブラリだけだと大変なケースでも、
Catsを使うとうまく関心事を分離して、クリーンかつ拡張に対して頑強になることがあります。
このスライドでは、そういった場合のCatsの使い所について、初学者向けに解説をしています。
2019年7月26日のセプテーニ・オリジナルでの社内勉強会資料です。
Taisuke Oe
July 26, 2019
Transcript
92 slides
-
ࣗݾհ Taisuke Oe / ຑ২ ହี Twitter: @OE_uia GitHub: @taisukeoe
Septeni Original, Inc. ٕज़ΞυόΠβʔ ScalaMatsuri ࠲ -
Catsͷ͍ํ build.sbt ʹҎԼͷ2ߦΛՃ Cats 1.6.1࠷৽stable൛ͰɺScala 2.11, 2.12ʹରԠɻ Scala 2.13Λ༻͢Δ߹ɺCats 2.0.0-M4͕࠷৽
scalacOptions += "-Ypartial-unification" libraryDependencies += "org.typelevel" %% "cats-core" % "1.6.1" -
List[Either[Error, Int]] val eitherList: List[Either[Error, Int]] = List(Right(1), Right(2), Right(3))
eitherList.foldLeft(Right(0):Either[Error, Int]) { case (Right(v1), Right(v2)) => Right(v1 + v2) case (Right(_), l @ Left(_)) => l case (l @ Left(_), _) => l } foldLeftͰɺཁૉܕͷߏͷղ͕ඞཁ ߏ͕ਂ͘ωετ͢Δ΄Ͳɺίʔυྔ͕૿͑Δɻ ࠶ར༻͠ʹ͘͘ͳΔɻ -
ʮListͷΈࠐΈʯΛׂ List(1, 2, 3).foldLeft(0)(_ + _) ͠ࢉ …… (_ +
_) ۭͷ …… 0 ΈࠐΈํ …… foldLeft -
͠ࢉ Either[Error, Int]ܕ ͷ͠ࢉʹɺߏͷ ղ͕ඞཁ Right(1) + Right(2) / /
Right(3) ޭInt͕ɺΫϥε(ྫ: Price)ʹมΘͬ ͯɺ࠶ར༻͍ͨ͠ -
Semigroup (༁) ܕΫϥεͷҰछ ೋ߲ԋࢉͰ͖Δ ݁߹ଇ(Associative Law)Λຬͨ͢ (A |+| B) |+|
C = A |+| (B |+| C) நϝιουɺ`combine` -
Semigroupͷ͍ํ import cats._ import cats.implicits._ 1 |+| 2 // 3
Option(1) |+| Option(2) // Some(3) (Right(1): Either[Error, Int]) |+| (Right(2): Either[Error, Int]) // Right(3) -
Semigroup[T]ͷ ͜͏͍͏ͷ͕Catsʹେྔʹఆٛ͞ ΕͯΔʢ࣮ࡍʹͬͱෳࡶʣ implicit val semigroupInt: Semigroup[Int] = ??? implicit
def semigroupEither[L,R](implicit E:Semigroup[R]): Semigroup[Either[L,R]] = ??? -
Semigroupͷྫ String Int Double Option[T] ୠ͠T: Semigroup Either[A, B] ୠ͠B:
Semigroup List[T] Map[K, V] ୠ͠V: Semigroup -
OptionܕΛฦ͢.some import cats._ import cats.implicits._ 1.some |+| 2.some //Some(3) 1.some
|+| none //Some(1) 1.asRight[Error] |+| 2.asRight[Error] //Right(3) -
Monoidͷྫ String Int Double Option[T] T: Semigroup Either[A, B] B:
Monoid List Map[K, V] V: Semigroup -
Foldableͷ͍ํ ͰIntͷΘΓʹɺಠࣗఆٛͷΫϥ εΛ͍͍ͨ߹…? import cats._, cats.implicits._ Foldable[List].fold(List(1,2,3)) // 6 Foldable[List].fold(List(1.asRight[Error],
2.asRight[Error])) // Right(3) Foldable[List].fold(List(1.asRight[Error], MyError().asLeft[Int])) // Left(MyError) -
Ϋϥε Price case class Price(private val value: Int) extends AnyVal
{ def +(p: Price): Price = this.copy(value = value + p.value) } implicit val priceMonoid: Monoid[Price] = new Monoid[Price] { override def empty: Price = Price(0) override def combine(x: Price, y: Price): Price = x + y } import cats._, cats.implicits._ Foldable[List].fold( List(Price(100).asRight[Error], Price(200).asRight[Error]) ) //Price(300) -
A. Listͷfoldϝιουͱ িಥ͢Δ͔Β def myFold[F[_]: Foldable, A: Monoid](list: F[A]): A
= list.fold ͳΒOKʢFListͰͳ͍) -
Լ४උ trait Product case class GoodProduct(id: Long, price: Price) extends
Product case class NiceProduct(id: Long, price: Price) extends Product trait ProductRepository[F[_], T <: Product] { def resolveById(id: Long): F[T] } val goodRepo = new ProductRepository[Future, GoodProduct]{ override def resolveById(id: Long): Future[GoodProduct] = ??? } val niceRepo = new ProductRepository[Future, NiceProduct]{ override def resolveById(id: Long): Future[NiceProduct] = ??? } def taxing(product: Product): Future[Price] = ??? -
Futureͷ߹: ྻ FutureΠϯελϯεͷੜ͕ɺଞͷFutureͷܭࢉ݁Ռʹґଘ ͍ͯ͠Δ߹ forࣜͰ؆୯ʹ߹Ͱ͖Δɻ val taxedPrice = for {
product <- goodRepo.resolveById(1L) taxed <- taxing(product) } yield taxed ͋ΔͷՁ֨(੫ࠐ)Λܭࢉ -
Futureͷ߹: ฒྻ ߹͞ΕΔFutureಉ࢜ʹɺґଘ͕ؔͳ͍߹ FutureΠϯελϯεੜ࣌ʹධՁ͕࢝·Δɻforࣜͷ֎Ͱ FutureΛੜ͠ͳ͚ΕͳΒͳ͍ͷ͕հɻ val niceF = niceRepo.resolveById(2L) val
sumOfPrice = for { good <- goodRepo.resolveById(1L) nice <- niceF } yield good.price + nice.price ෳͷͷՁ֨(੫ൈ)Λ߹ܭ͢Δɻ -
ෳͷྻܭࢉΛฒྻʹ ՄೳͳݶΓฒྻʹ߹ͯ͠ΈΔ val niceF = niceRepo.resolveById(2L) val both = for
{ good <- goodRepo.resolveById(1L) taxedGoodF = taxing(good) nice <- niceF taxedNice <- taxing(nice) taxedGood <- taxedGoodF } yield taxedGood + taxedNice ෳͷͷՁ֨(੫ࠐ)Λ߹ܭ͢Δɻ -
ෳͷྻܭࢉΛฒྻʹ forࣜΛׂ͢ΔͱɺزϚγɻ val taxedGood = for { product <- goodRepo.resolveById(1L)
taxed <- taxing(product) } yield taxed val taxedNice = for { product <- niceRepo.resolveById(2L) taxed <- taxing(product) } yield taxed for { goodPrice <- taxedGood nicePrice <- taxedNice } yield goodPrice + nicePrice ෳͷͷՁ֨(੫ࠐ)Λ߹ܭ͢Δɻ -
ฒྻܭࢉΛ߹ ApplicativeελΠϧͰฒྻܭࢉΛ߹͍͢͠ import cats._ import cats.implicits._ (goodRepo.resolveById(1L).flatMap(taxing), niceRepo.resolveById(2L).flatMap(taxing)).mapN(_ + _)
ෳͷͷՁ֨(੫ࠐ)Λ߹ܭ͢Δɻ Applicative[Future].map2( goodRepo.resolveById(1L).flatMap(taxing), niceRepo.resolveById(2L).flatMap(taxing))(_ + _) -
ฒྻܭࢉΛ߹ ฒྻͯ͠औಘ/ݕূͨ͠ܭࢉΛɺϑΝΫτϦϝ ιουʹ؆୯ʹྲྀ͠ࠐΊΔ import cats._ import cats.implicits._ case class User(name:
String, age: Int) val nameFuture: Future[String] = ??? val ageFuture: Future[Int] = ??? (nameFuture, ageFuture).mapN(User.apply) -
͜͜ͰRepositoryͷվम ΤϥʔΛEitherܕͰදݱ͢Δ͜ͱʹͳͬͨ Ͳ͏͢Εܭࢉ݁ՌΛ߹Ͱ͖Δʁ type EitherE[T] = Either[Error, T] type FutureEitherE[T]
= Future[EitherE[T]] val goodERepo = new ProductRepository[FutureEitherE, GoodProduct]{ override def resolveById(id: Long): FutureEitherE[GoodProduct] = ??? } val niceERepo = new ProductRepository[FutureEitherE, NiceProduct]{ override def resolveById(id: Long): FutureEitherE[NiceProduct] = ??? } -
ApplicativeͱMonadͷҧ͍ Applicative[Future].compose[EitherE].map2( goodERepo.resolveById(1L), niceERepo.resolveById(2L))(_.price + _.price) Applicative[Future].compose[EitherE].map2( goodERepo.resolveById(1L).flatMap(taxing), niceERepo.resolveById(2L).flatMap(taxing))(_ +
_) ίϯύΠϧͰ͖Δ ੫ۚͷܭࢉΛ͢ΔͱɺίϯύΠϧͰ͖ͳ͍ Monadͷ߹(flatMap)ͰίϯύΠϧΤϥʔ -
EitherT[Future, A, B] type EitherTFuture[T] = EitherT[Future, Error, T] val
goodETRepo = new ProductRepository[EitherTFuture, GoodProduct] { override def resolveById(id: Long): EitherTFuture[GoodProduct] = ??? } val niceETRepo = new ProductRepository[EitherTFuture, NiceProduct] { override def resolveById(id: Long): EitherTFuture[NiceProduct] = ??? } -
EitherT[Future, A, B] Applicative[EitherTFuture].map2( goodETRepo.resolveById(1L).flatMap(taxing), niceETRepo.resolveById(2L).flatMap(taxing))(_ + _) EitherTMonadɻ શͯͷMonadApplicativeͰ͋ΔͷͰɺEitherTApplicativeͰ
͋Δɻ Ͱtaxingͷγάωνϟ͕ҰகͤͣɺίϯύΠϧͰ͖ͳ͍ def taxingEF(product: Product): EitherTFuture[Price] = ??? EitherTFuture൛ͷtaxing͕ཉ͍͠ -
EitherT Future൛ ! val taxingEF = ɹɹ (taxing _).andThen(f =>
EitherT(f.map(_.asRight[Error]))) Applicative[EitherTFuture].map2( goodETRepo.resolveById(1L).flatMap(taxingEF), niceETRepo.resolveById(2L).flatMap(taxingEF))(_ + _) ࠓճͷtaxingͷΑ͏ͳɺMonadΛฦؔ͢Λ ߹ɾ֦ு͍ͨ͠ -
Kleisli Kleisli[F, A, B] A => F[B] ͷϥούʔ MonadΛੜ͢ΔؔΛϥοϓ͢Δ͜ͱ͕ଟ͍
͜ͷΑ͏ͳؔΛศརʹѻ͏ͨΊͷϝιου͕ଟ ɻ runϝιουͰɺதͷA => F[B]ΞΫηεՄೳ F͕MonadͰ͋ΕɺKleisli[F, A, B]Monad -
Kleisli ߹ def taxing(product: Product): Future[Price] = ??? def exchange(jpy:
Price): Future[PriceInUSD] = ??? // Function1ͷandThenʹΑΔ߹Ͱ͖ͳ͍ɻίϯύΠϧΤϥʔɻ // (taxing _) andThen exchange val taxingPriceInUSD = Kleisli(taxing) andThen exchange _ val taxingEFinUSD = taxingInUSD.mapF(f => EitherT(f.map(_.asRight[Error]))) Applicative[EitherTFuture].map2( goodETRepo.resolveById(1L).flatMap(taxingEFinUSD.run), niceETRepo.resolveById(2L).flatMap(taxingEFinUSD.run))(_ + _) -
Foldable .foldMapM List(1L, 2L, 3L).foldMapM( goodETRepo.resolveById _ andThen (_.map(_.price)) )
Repository͔ΒͷGoodProductऔಘ͕ྻ࣮ ߦ͞ΕΔ -
ࣗྗͰsequence val sequenced: Either[Error, List[Price]] = list.foldRight(List.empty[Price].asRight[Error]){ (e, acc) =>
for { value <- e valueList <- acc } yield value :: valueList } ґଘؔͷͳ͍(ฒྻ)ܭࢉ͕ొ͢Δɻ Applicativeͷ͍…… -
͞ΒʹֶͿʹ ʮܕͷάϧʔϓʯɺҰൠతͳ୯ޠͰ͋Γ·ͤΜɻ ຊདྷ ܕΫϥε ͱݺΕ·͢ɻ ܕΫϥε ʹ͍ͭͯɺཧղΛਂΊΔʹҎԼͷࢿྉ Λࢀর͍ͯͩ͘͠͞ɻ Cats |
Documentation Scalaʹ͓͚ΔܕΫϥεೖ