scalaプログラミング・マニアックス

44
Scala プログラミング マニアックス 20121130 浅海智晴

Upload: tomoharu-asami

Post on 31-May-2015

7.840 views

Category:

Documents


3 download

TRANSCRIPT

  • 1. Scala20121130

2. 3. Modegramming Style (DSL ) http://modegramming.blogspot.com/ SimpleModeler http://github.com/asami/simplemodeler/ SmartDox http://github.com/asami/smartdox g3 http://code.google.com/p/goldenport3/ g4 http://github.com/asami/goldenport-android-library/ 4. 5. Object-Functional Programming Monadic 6. Scala 2.9.2 Scalaz 6.0.4 Scala 2.10.0 M6 Scalaz 7 (20124?) Scala 2.10 Akka(Actor)STMFuture/Promise Scala 2.10 + Scalaz7 7. SSD NoSQL 8. DSL OO DSL OO OO 9. 10. () () 11. 20OO Haskell Scala(+scalaz) Lisp, ML, OCaml pure Lisp Parametric Subtypepolymorphism polymorphism 12. List, () ()() ( ) 13. 14. Algebraic data type case class Person(name: String, age: Int)Case class Company(name: String, phone: String)EitherEither[Person, Company]sealedsealed trait Partycase class Person(name: String, age: Int) extends Partycase class Company(name: String, phone: String) extends Party 15. Persistent data structure (Wikipedia) 16. (associative law) (semigroup) (monoid) (a + b) + c = a + (b + c) (group) (commutative law) a+b=b+a () (distributive law) (ring) (field)a * (b + c) = a * b + a * c 17. (category) Hask (Scala?) (monad) (kleisli category) Applicative (arrow,functormorphism) (functor) 18. 3 OO OO 19. (shared mutability) STM (Software Transactional Memory) () (isolatingmutability) SQL 20. Monadic Javadef 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) ! } !}! 21. Scala ()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) !} !} !} !Scalaz (Monadic)def validate(name: String, age: Int):ValidationNEL[Throwable, (String, Int)] = { ! (validateName(name) validateAge(age))((_, _)) !}!URL: http://modegramming.blogspot.jp/2012/04/ scala-tips-validation-10-applicative.html 22. Monad http://modegramming.blogspot.jp/2012/08/30-13- monad.html Monoid http://modegramming.blogspot.jp/2012/08/30-12- monoid.html Fold http://modegramming.blogspot.jp/2012/07/30-10- map-filter-fold.html 23. Arrow 24. 25. map M[A]M[B] filter M[A]M[A] /fold M[A]N N/A N/AreduceM[A]A N/A N/Acollect M[A]M[B] /flatMap M[A]M[B] // 26. Object Functional Programming (OFP) 27. JavaScala 28. OFP (trait) mix-in AOP (monad) Monadic (type class) (?) Scala 29. mixin Scala Cake Dependency Injection http://www.crosson.org/2012/03/dependency-injection-using-scala-traits.html http://www.warski.org/blog/2010/12/di-in-scala-cake-pattern/ http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di/ 30. DSL for Framework Scalable Language = Scala APIDSL API DSL 31. (1) 32. (2) 33. DSL:SparkScaldingval file = spark.textFile("hdfs://...")file.flatMap(line => line.split(" ")).map(word => (word, 1)) Spark.reduceByKey(_ + _)class WordCountJob(args : Args) extends Job(args) {TextLine( args("input") ).read. flatMap(line -> word) { line : String => line.split("s+") }. groupBy(word) { _.size }. write( Tsv( args("output") ) )}Scalding https://github.com/twitter/scalding CascadingScala DSL Collection APIHadoop 34. Monadic 35. Monadic Monad MonadFunctor DSL 36. def main(args: Array[String]) { records |> build >>> buildTree >>> showTree }def build(records: Seq[Map[Symbol, Any]]): Map[Int, ] = {records.foldRight(Map[Int, ]())((x, a) => {val ID = x(ID).asInstanceOf[Int]val = x().asInstanceOf[String]val ID = x(ID).asInstanceOf[Option[Int]]val = x.get().asInstanceOf[Option[String]]a + (ID -> (ID, , ID, ))})}def buildTree(sections: Map[Int, ]): Tree[] = {def build(sec: ): Tree[] = {val children = sections collect {case (k, v) if v.ID == sec.ID.some => v}node(sec, children.toStream.sortBy(_.ID).map(build))}build(sections(1))}def showTree(tree: Tree[]) {println(tree.drawTree(showA[]))} 37. val records = List(Map(ID -> 1, -> "", Map(ID -> 121,ID -> None, -> "", -> None), ID -> Some(12), Map(ID -> 11, -> ""), -> "", Map(ID -> 122,ID -> Some(1), -> "", -> ""), ID -> Some(12), Map(ID -> 12, -> ""), -> "",Map(ID -> 123,ID -> Some(1), -> "", -> ""), ID -> Some(12), Map(ID -> 13, -> ""), -> "", Map(ID -> 124,ID -> Some(1), -> "", -> ""), ID -> Some(12), Map(ID -> 111, -> ""), -> "",Map(ID -> 125,ID -> Some(11), -> "", -> ""), ID -> Some(12), Map(ID -> 112, -> ""), -> "", Map(ID -> 131,ID -> Some(11), -> "", -> ""), ID -> Some(13), Map(ID -> 113, -> ""), -> "",Map(ID -> 132,ID -> Some(11), -> "", -> ""), ID -> Some(13), Map(ID -> 114, -> ""), -> "",Map(ID -> 133,ID -> Some(11), -> "", -> ""), ID -> Some(13), -> "")) 38. (1,,None,Some(None))|+- (11,,Some(1),Some())| || +- (111,,Some(11),Some())| || +- (112,,Some(11),Some())| || +- (113,,Some(11),Some())| || `- (114,,Some(11),Some())|+- (12,,Some(1),Some())| || +- (121,,Some(12),Some())| || +- (122,,Some(12),Some())| || +- (123,,Some(12),Some())| || +- (124,,Some(12),Some())| || `- (125,,Some(12),Some())|`- (13,,Some(1),Some()) | +- (131,,Some(13),Some()) | +- (132,,Some(13),Some()) | `- (133,,Some(13),Some()) 39. def go[T](a: => T): (T, Long) = {val start = System.currentTimeMillis val f = (x: Int) => {val r = aThread.sleep(x * 100)val end = System.currentTimeMillis x(r, end - start) }}scala> go(f(10)) scala> go {res176: (Int, Long) = (10,1000) | f(10)|} res253: (Int, Long) = (10,1001) 40. PromiseKleisliscala> val fp = f.promisefp: scalaz.Kleisli[scalaz.concurrent.Promise,Int,Int] =scalaz.Kleislis$$anon$1@9edaab8 Applicativescala> go((fp(1) |@| fp(2) |@| fp(3))(_ + _ + _).get)res215: (Int, Long) = (6,302)scala> go(f(1) + f(2) + f(3))res212: (Int, Long) = (6,603)scala> go((1.some |@| 2.some |@| 3.some)(_ + _ + _).get)res237: (Int, Long) = (6,1) 41. scala> go(List(1, 2, 3).map(fp).map(_.flatMap(fp)).sequence.get)res220: (List[Int], Long) = (List(1, 2, 3),602)scala> go(List(1, 2, 3).map(f).map(f))res221: (List[Int], Long) = (List(1, 2, 3),1205)val fx = (x: Int) => {val t = math.abs(x - 4)Thread.sleep(t * 100)x}val fxp = fx.promise 42. scala> go(List(1, 2, 3).map(fp).map(_.flatMap(fxp)).sequence.get)res222: (List[Int], Long) = (List(1, 2, 3),402) 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(f >>> fx)) res232: (List[Int], Long) = (List(1, 2, 3),1205) 43. OFP DSL Scalable Laguage = Scala Scala OFPScala 44. END