オブジェクト指向開発におけるobject-functional programming

70
オブジェクト指向開発における Object-Functional Programming 20141114 Everforth 浅海智晴

Upload: tomoharu-asami

Post on 02-Jul-2015

1.918 views

Category:

Technology


1 download

TRANSCRIPT

  • 1. Object-Functional Programming20141114Everforth

2. 1985() UNIX/OSWeb 20019 Java, XML, UML 2005420073 () BusinessPlace () Everforth CTO 3. ApparelCloudhttp://www.apparel-cloud.com/ 4. ApparelCloud 5. ApparelCloudApparel Cloud Apparel Cloudapparel-webCDBPaasverforthApparel CloudIaaSAmazonOptionSaaSapparel-webApparel Cloud Private ProjectApparel CloudA5BlogSHOPLIKEetcOptionEC(PV,likeetcoptionPCAPI(APIPUSH 6. Monadic ProgrammingObject-Functional ProgrammingOFP 7. 8. SSD NoSQL 9. DSL OO OODSL OO 10. 11. API vs DSL 12. 13. ApparelCloudScalaJavaScalaScalaScalaJavaScalaJava 14. EverforthEverforh Engine(Mindmap)(+API)(DSL) (Scala)EverforthModelerService(Scala)(S, LTSV)Extension(Scala)Service(Scala)Extension(Scala)ScalaScala114Kstep140Kstep 15. 16. Scala Java DSL (Domain Specific Language) DSL, DSL JavaVM Java 17. Scala(ble)Web 18. () () 19. pure Lisp Lisp, ML, OCaml Subtypepolymorphism Haskell Scala(+scalaz) Parametricpolymorphism20OO 20. List, () ()() ( ) 21. 22. (associative law) (semigroup) (monoid) (group) (commutative law) () (distributive law) (ring) (field)(a + b) + c = a + (b + c)a + b = b + aa * (b + c) = a * b + a * c 23. (category) Hask (Scala?) (kleisli category) (arrow,morphism)(functor)(monad)Applicativefunctor 24. (recursion) (high-order function) (immutable data) (lazy evaluation) (referential transparency) () (substitution model) (equational reasoning) (algebraic data type) , (direct product, direct sum) (persistent data structure) (effect) (type class) (monad) 25. A B AB (,substitution model) AB (no side effect) AB (, referentialtransparency) (imply) (arrow, morphism) Reader def f(x: A): B 26. 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 27. A A A A B C A, B, C A f(x: A, y: A): A 1 + 1 2 abc + xyz abcxyz List(abc) ++ List(xyz) List(abc, xyz) 28. A M[B] A B BM[B] MMB bind(flatMap) Reader Transformer(Kleisli) def flatMap[A, B](f: A = List[B]) 29. AA Endo Monoid SSA State SM[SA] State Transformer 30. Algebraic data type (direct product) () Tuple Case class (direct sum) () Either sealed trait/abstract class + case class/case object 31. 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 32. Persistent data structure (Wikipedia) 33. In computer science, a type class is a type systemconstruct that supports ad hoc polymorphism. Thisis achieved by adding constraints to type variables inparametrically polymorphic types. (Wikipedia) OOP OOP OOP Scala 34. case class Average(total: Double, count: Int) {def value = total / countdef +(rhs: Average) = Average(total + rhs.total, count + rhs.count)}object Average {implicit object AverageMonoid extends Monoid[Average] {def append(lhs: Average, rhs: = Average) = lhs + rhsdef zero = Average(0, 0)}} 35. object MonoidSample {import Average.AverageMonoiddef concatenate[T: Monoid](xs: Vector[T]): T = {val C = implicitly[Monoid[T]]xs.foldLeft(C.zero)((z, x) = z |+| x)}def sample {val a: Int = concatenate(Vector(1, 2, 3))assert(a == 6)val b: Average = concatenate[Average](Vector(Average(1.0, 1), Average(2.0, 2), Average(3.0, 3)))assert(b == Average(6.0, 6))}def main(args: Array[String]) {sample}} 36. Monadic Programming 37. MonadsEugenio Moggia program is an arrow of a Kleisli category(Kleislitriple)(Wikipedia) In functional programming, a monad is a structure thatrepresents computations defined as sequences of steps: atype with a monad structure defines what it means tochain operations, or nest functions of that type together.This allows the programmer to build pipelines thatprocess data in steps, in which each action is decoratedwith additional processing rules provided by the monad.(Wikipedia) () 38. (List, Vector) (Option) map, filter, collect flatMap Free, Operational 39. Option / List () Vector () Stream Try Future 40. http://ja.wikibooks.org/wiki/Haskell/%E5%9C%8F%E8%AB%96 41. Scalaz https://github.com/scalaz/scalaz : Scalaz: Type Classes and Pure Functional DataStructures for Scala : An extension to the core Scala library for functionalprogramming. http://typelevel.org Scala 42. MonadicJavadef validate(name: String, age: Int): ValidationNEL[Throwable, (String,Int)] = {!val a = validateName(name) !val b = validateAge(age) !if (a.isSuccessb.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) !} !}! 43. 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 44. 45. StateState MonadState Funcion Function FunctionStateValueValue Value ValueValue Value 46. Statecase class Stack(stack: List[Int])def main(args: Array[String]) {sample}def sample {val stack = Stack(Nil)val r = pipe.run(stack)assert(r == (Stack(List(10)), 10), s$r)} 47. val pipe: State[Stack, Int] = {for {a - push(10)b - push(a)c - pop} yield c}def push(x: Int) = State[Stack, Int] { s =(Stack(x :: s.stack), x)}def pop = State[Stack, Int] { s =s.stack match {case x :: xs = (Stack(xs), x)case Nil = ???}} 48. (shared mutability) STM (Software Transactional Memory) () (isolatingmutability) 49. 50. Future case class Site(uri: String, page: String)def largestSite: Future[Site] = {for {a - future(getSite(http://www.yahoo.com))b - future(getSite(http://www.amazon.com))c - future(getSite(http://www.google.com))} yield {Vector(a, b, c).maxBy(_.page.length)}}def getSite(uri: String): Site = {Site(uri, new URL(uri).asInput.string)}def main(args: Array[String]) {largestSite.onSuccess {case site = println(swin = ${site.uri})}} 51. RxJava - Scala Functional Reactive Programming https://github.com/Netflix/RxJava http://techblog.netflix.com/2013/02/rxjava-netflix-api.htmldef simpleComposition() {// fetch an asynchronous ObservableString// 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})} 52. scalaz stream Functional Reactive Programming https://www.chrisstucchio.com/blog/2014/scalaz_streaming_tutorial.htmlfor {bag - resource.managed(new FileBag())bag2 - resource.managed(new FileBag())bag3 - resource.managed(new FileBag())} {Process.constant(4096).through(io.chunkR(new URL(http://scala-lang.org/).openStream)).to(bag.chunkW).run.runbag.chunksR(4096).to(bag2.chunkW).run.runbag2.linesR.map(_ + n).pipe(text.utf8Encode).to(bag3.chunkW).run.runbag.size should be (bag2.size)bag.size should be (bag3.size)} 53. Spark RDD (Resilient Distributed Dataset) http://www.cs.berkeley.edu/~pwendell/strataconf/api/core/spark/RDD.htmlscala val textFile = sc.textFile(README.md)textFile: spark.RDD[String] = spark.MappedRDD@2ee9b6e3scala val linesWithSpark = textFile.filter(line =line.contains(Spark))linesWithSpark: spark.RDD[String] = spark.FilteredRDD@7dd4af09scala textFile.filter(line = line.contains(Spark)).count() // Howmany lines contain Spark?res3: Long = 15 54. Object FunctionalProgramming 55. OFP (trait) mix-in AOP (monad) Monadic (type class) (?) Scala 56. 57. OOP/FP 58. 59. DSL (Domain Specific Language) () DSL DSL () DSL XMLS Scala DSL 60. DSLAnormSQL(select name from coffees where price10.0)Squerylfrom(coffees)(s =where(s.price10.0)select(s))Slickcoffees.filter(_.price10.0).map(_.name) 61. DSLdef transaction[T](body: = T) = {val tx = openTransaction()try {body} finally {closeTransaction(tx)}}case class Conditional[T](p: Boolean, truebody: () = T) {def myelse(falsebody: = T): T = if (p) truebody() else falsebody}def myif[T](p: Boolean)(truebody: = T): Conditional[T] =new Conditional(p, () = truebody) 62. def sample(v: Boolean): Boolean = {transaction {myif (v) {true} myelse {false}}} 63. +OFP 64. 65. 66. 67. 68. OMT v1 (1991) Object model Dynamic model Functional model OMT v2 (2005) Class model Dynamic model Interaction model BigData 69. DSL Monadic Programming Functional Reactive Programming OFP (Object-Functional Programming) DSL OP : FP = 6 : 4 () + OFP DSL 70. END