実務者のためのかんたんscalaz

63
実務者のための かんたんScalaz 201477 Everforth 浅海智晴

Upload: tomoharu-asami

Post on 31-May-2015

3.213 views

Category:

Technology


3 download

DESCRIPTION

Scala

TRANSCRIPT

  • 1. ! Scalaz 201477 Everforth

2. Scala Scala Scala / 3. Monadic Scalaz Scalaz Monoid 4. 5. Object Functional Programming Scalaz 6. SSD NoSQL 7. OFAD/ OFADOOAD OFP UCD/UX Scala DSL DDD DCI CQRS EIP EDA 8. DSL OO OO DSL OO 9. Scalaz https://github.com/scalaz/scalaz : Scalaz: Type Classes and Pure Functional Data Structures for Scala : An extension to the core Scala library for functional programming. http://typelevel.org Scala 10. 11. () () 12. pure Lisp Lisp, ML, OCaml Subtype polymorphism Haskell Scala(+scalaz) Parametric polymorphism 20 OO 13. List, () ()() ( ) 14. 15. (semigroup) (monoid) (group) (associative law) () (commutative law) (ring) (field) (distributive law) (a + b) + c = a + (b + c) a + b = b + a a * (b + c) = a * b + a * c 16. (category) Hask (Scala?) (kleisli category) (arrow, morphism) (functor) Applicative functor (monad) 17. DSL / 18. 3 (A B) 19. Scalaz Monoid Tree, NonEmptyList EphemeralStream Cord, Rope Foldable, Traverse Monadic / 20. A B AB (, substitution model) AB (no side effect) A B (, referential transparency) (arrow, morphism) (imply) def f(x: A): B 21. A B C 2 A B(1) A (B C) ABC def f(a: A, b: B): C def f(a: A)(b: B): C def f(a: A): B => C val f: A => B => C 22. A A A A B C A, B, C f(x: A, y: A): A 1 + 1 2 abc + xyz abcxyz List(abc) ++ List(xyz) List(abc, xyz) 23. A M[B] A B BM[B] MMB bind def flatMap[A, B](f: A => List[B]) 24. http://ja.wikibooks.org/wiki/Haskell/%E5%9C%8F%E8%AB%96 25. Monadic def validate(name: String, age: Int): ValidationNEL[Throwable, (String, Int)] = {! val a = validateName(name) ! val b = validateAge(age) ! if (a.isSuccess && b.isSuccess) { ! val a1 = a.asInstanceOf[Success[NonEmptyList[Throwable], String]].a ! val b1 = b.asInstanceOf[Success[NonEmptyList[Throwable], Int]].a ! Success((a1, b1)) ! } else if (a.isSuccess) { ! b.asInstanceOf[Failure[NonEmptyList[Throwable], (String, Int)]] ! } else if (b.isSuccess) { ! a.asInstanceOf[Failure[NonEmptyList[Throwable], (String, Int)]] ! } else { ! val a1 = a.asInstanceOf[Failure[NonEmptyList[Throwable], String]].e ! val b1 = b.asInstanceOf[Failure[NonEmptyList[Throwable], Int]].e ! Failure(a1 |+| b1) ! } ! }! Java 26. def validate(name: String, age: Int): ValidationNEL[Throwable, (String, Int)] = { ! validateName(name) match { ! case Success(a) => validateAge(age) match { ! case Success(b) => Success((a, b)) ! case Failure(e) => Failure(e) ! } ! case Failure(e1) => validateAge(age) match { ! case Success(b) => Failure(e1) ! case Failure(e2) => Failure(e1 |+| e2) ! } ! } ! } ! def validate(name: String, age: Int): ValidationNEL[Throwable, (String, Int)] = { ! (validateName(name) validateAge(age))((_, _)) ! }! Scala () Scalaz (Monadic) URL: http://modegramming.blogspot.jp/2012/04/ scala-tips-validation-10-applicative.html 27. 28. Arrow 29. 30. (1) 31. (2) 32. map M[A]M[B] filter M[A]M[A] / fold M[A]N N/A N/A reduce M[A]A N/A N/A collect M[A]M[B] / flatMap M[A]M[B] // 33. Algebraic data type case class Person(name: String, age: Int) Case class Company(name: String, phone: String) Either[Person, Company] Either sealed sealed trait Party case class Person(name: String, age: Int) extends Party case class Company(name: String, phone: String) extends Party 34. Persistent data structure (Wikipedia) 35. (shared mutability) STM (Software Transactional Memory) () (isolating mutability) SQL 36. def go[T](a: => T): (T, Long) = { val start = System.currentTimeMillis val r = a val end = System.currentTimeMillis (r, end - start) } val f = (x: Int) => { Thread.sleep(x * 100) x } scala> go(f(10)) res176: (Int, Long) = (10,1000) scala> go { | f(10) | } res253: (Int, Long) = (10,1001) 37. scala> val fp = f.promise fp: scalaz.Kleisli[scalaz.concurrent.Promise,Int,Int] = scalaz.Kleislis$$anon$1@9edaab8 scala> go((1.some |@| 2.some |@| 3.some)(_ + _ + _).get) res237: (Int, Long) = (6,1) scala> go(f(1) + f(2) + f(3)) res212: (Int, Long) = (6,603) scala> go((fp(1) |@| fp(2) |@| fp(3))(_ + _ + _).get) res215: (Int, Long) = (6,302) PromiseKleisli Applicative 38. scala> go(List(1, 2, 3).map(f).map(f)) res221: (List[Int], Long) = (List(1, 2, 3),1205) scala> go(List(1, 2, 3).map(fp).map(_.flatMap(fp)).sequence.get) res220: (List[Int], Long) = (List(1, 2, 3),602) val fx = (x: Int) => { val t = math.abs(x - 4) Thread.sleep(t * 100) x } val fxp = fx.promise 39. scala> go(List(1, 2, 3).map(f >>> fx)) res232: (List[Int], Long) = (List(1, 2, 3),1205) scala> go(List(1, 2, 3).map(f).map(fx)) res223: (List[Int], Long) = (List(1, 2, 3),1205) scala> go(List(1, 2, 3).map(fp >=> fxp).sequence.get) res230: (List[Int], Long) = (List(1, 2, 3),402) scala> go(List(1, 2, 3).map(fp).map(_.flatMap(fxp)).sequence.get) res222: (List[Int], Long) = (List(1, 2, 3),402) 40. DSL Anorm Squeryl Slick SQL("""select name from coffees where price < 10.0"") from(coffees)(s => where(s.price < 10.0) select(s)) coffees.filter(_.price < 10.0).map(_.name) 41. (immutable) (immutable) (no side) 42. scalaz stream com.everforth.lib.util.FileBag for { bag line.contains("Spark")) linesWithSpark: spark.RDD[String] = spark.FilteredRDD@7dd4af09 scala> textFile.filter(line => line.contains("Spark")).count() // How many lines contain "Spark"? res3: Long = 15 44. RxJava - Scala Functional Reactive Programming https://github.com/Netflix/RxJava http://techblog.netflix.com/2013/02/rxjava-netflix-api.html def simpleComposition() { // fetch an asynchronous Observable // that emits 75 Strings of 'anotherValue_#' customObservableNonBlocking() // skip the first 10 .skip(10) // take the next 5 .take(5) // transform each String with the provided function .map({ stringValue -> return stringValue + "_transformed"}) // subscribe to the sequence and print each transformed String .subscribe({ println "onNext => " + it}) } 45. Object Functional Programming 46. OFP mix-in AOP (trait) Monadic (monad) (?) Scala (type class) 47. (1) 48. (2) 49. 50. :: A :: Try() B :: :: 51. (Throwable) try, catch, finally 52. Option / scala Try scala.util Either scala.util Validation scalaz / ( ) scalaz Future () scala.concurren t Promise () scalaz.concurre nt Task () scalaz.concurre nt 53. Scalaz 54. : Boolean scala> def bt: Boolean = true bt: Boolean scala> def bf: Boolean = false bf: Boolean scala> bt option 100 res8: Option[Int] = Some(100) scala> bf option 100 res9: Option[Int] = None scala> bt ?? 100 res11: Int = 100 scala> bf ?? 100 res10: Int = 0 scala> bt !? 100 res12: Int = 0 scala> bf !? 100 res13: Int = 100 55. : Option scala> val os = 100.some os: Option[Int] = Some(100) scala> val on = none[Int] on: Option[Int] = None scala> os ? "defined" | "undefined res14: String = defined scala> on ? "defined" | "undefined res15: String = undefined scala> on.orZero res16: Int = 0 scala> os | -1 res18: Int = 100 scala> on | -1 res17: Int = -1 scala> os.cata(_ + 1, -1) res19: Int = 101 scala> on.cata(_ + 1, -1) res20: Int = -1 56. Monoid http://ja.wikipedia.org/wiki/ %E3%83%A2%E3%83%8E%E3%82%A4%E3%83%89 A A A 2 1 + 2 = 3 abc + mno = abcmno List(abc) ++ List(mno) = List(abcmno) 57. (1 + 2) + 3 == 1 + (2 + 3) (abc + mno) + xyz == abc + (mno + xyz) 1 + 0 == 0 + 1 == 1 abc + == + abc == abc 58. Monoid def sumi(xs: Vector[Int]): Int = sumi2(xs, 0) def sumi2(xs: Vector[Int], acc: Int): Int = { xs.headOption match { case None => acc case Some(x) => sum(xs.tail, acc + x) } } 59. Monoid def summ[T: Monoid](xs: Vector[T]): T = { val M = implicitly(Monoid[T]) summ2(xs, M.zero) } def summ2[T: Monoid](xs: Vector[T], acc: T): T = { xs.headOption match { case None => acc case Some(x) => summ2(xs.tail, acc |+| x) } } 60. : Monoid scala> val xs = Vector(1, 2, 3) val xs = Vector(1, 2, 3) xs: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3) scala> xs.concatenate xs.concatenate res3: Int = 6 scala> xs.foldLeft(0) { (z, x) => z + x } xs.foldLeft(0) { (z, x) => z + x } res4: Int = 6 scala> xs.foldLeft(0) { (z, x) => z |+| x } xs.foldLeft(0) { (z, x) => z |+| x } res5: Int = 6 61. : Monoid scala> xs.foldMap(x => x) res87: Int = 6 scala> xs.foldMap(x => x + 1) res88: Int = 9 62. Scalaz OK Scalaz Monoid Scalaz 63. END