Advertisement
Advertisement

More Related Content

Advertisement

Recently uploaded(20)

Advertisement

Thinking in Cats

  1. Thinking in Cats eugene yokota (@eed3si9n) Typesafe March 2016, ScalaMatsuri
  2. 文字数制限あり。折りたたみやエンコーディングは無し。 • Reactive Platform team at Typesafe • a commercial development platform for pros • tech lead of Typesafe で仕事しています About me
  3. 文字数制限あり。折りたたみやエンコーディングは無し。Cats というライブラリの話 Cats
  4. Cats は Scala プログラミング言語で関数型プログラミングを するための抽象化を提供するライブラリ Cats is a library to provide abstraction for functional programming in the Scala programming language.
  5. Cats: Scala の型システムを利用して式を用いたプログラミン グの支援するためのライブラリ Cats is a library to provide abstraction for programming with expressions (functional programming) making use of the type system (in the Scala programming language).
  6. 文字数制限あり。折りたたみやエンコーディングは無し。 hard cats soft cats 2種類の猫
  7. software doesn’t exist in a vacuum ソフトウェアは真空状態に存在するものではない
  8. software doesn’t exist in a vacuum 水、酸素、光、土壌など • water • oxygen • light • soil (nutrients, pH)
  9. software doesn’t exist in a vacuum 継続的にメンテ(進化)するための開発リソース、セオリー、 コミュニティ、周辺プラグイン、ドキュメンテーション • development resource to
 maintain/evolve the system • underlying theory • user community • surrounding plugins/libraries • documentation
  10. 60 contributors + 547 pull requests in an year. コントリビュータは色んな所から集まってきてる pull req も一年で 547 本と活発
  11. d6 (also known as non, Erik) d6 の人柄みたいなのが、ライブラリの方針に反映されている
  12. motivations とっつきやすさ、モジュール性、ドキュメンテーション、 効率性 •Approachability •Modularity •Documentation •Efficiency
  13. see also Principles for Modular, Functional, Approachable Libraries (video, slides) goals 関数型、安全、高速、ドキュメントが整備されている、 モジュラー、慣用的、実用的、協調、友好的 •Functional •Safe •Fast •Documented •Modular •Idiomatic •Pragmatic •Collaborative •Welcoming
  14. see also Principles for Modular, Functional, Approachable Libraries (video, slides) goals Scala で関数型プログラムをおこなう障壁を取り除く “Remove barriers to doing functional programming in Scala.”
  15. see also Principles for Modular, Functional, Approachable Libraries (video, slides) barriers 技術的な障壁: 複雑さ、職場での障壁: 未知への恐怖、 社会的な障壁: 「これは僕のためのものじゃない」 • technical barriers: complexity (e.g. typeclass is not first class) • barriers at work: fear of the unknown (e.g. performance concerns) • social barriers: “This is not for me” (e.g. imposter syndrome and delayed feelings of mastery)
  16. see also Principles for Modular, Functional, Approachable Libraries (video, slides) we should 安定した長期的で協力的なコミュニティを促進するために、 新境地を開拓しつつ、高品質なライブラリを提供する • be willing to break new ground (e.g. build-your-own- runtime) • provide high-quality libraries (e.g. documentation, benchmarks) • foster a stable, long-term, supportive community • model good technical and social practices • reach out and welcome newcomers • acknowledge the limits of our own knowledge • provide opportunities for new work • accept responsibility for education and codes of conduct
  17. プログラマが行う作業: 問題ドメインをモデル化して、 コンピュータで実行させる problem domain model computer what we do
  18. fp では問題ドメインから時系列を抜いて、 データ型と演算子に分け、それを計算機で評価する problem domain computer fp datatype operators
  19. 合成可能性、論理的な推論可能性 problem domain computer fp datatype operators •composability •reasonable
  20. 演算子がデータ型の関係性を記述する 型クラスによる抽象化 problem domain computer fp datatype operators •composability •reasonable •typeclasses
  21. 評価器としてのインタプリタ 制御された作用、高性能化など problem domain interpretor fp datatype operators evaluate •controlled effects
  22. 「型システムとは、(中略) プログラムがある種の振る舞いを起 こさないことを保証する構文的手法である。」TAPL から soundness “A type system is a syntactic method for automatically checking the absence of certain erroneous behaviors…”
  23. 健全性: 論証が妥当であり、かつ前提の全てが真であること soundness •argument is valid (all cups are green; Socrates is a cup; therefore, Socrates is green.) P→Q •all premise is true P ~ true
  24. これはコンパイルが通るべきではない soundness? scala> "1" == 1 res0: Boolean = false this should not compile
  25. 等価性はこのように定義されるべき equality trait Eq[A] {   def equal(a1: A, a2: A): Boolean }
  26. Cats での等価性 equality scala> import cats._, cats.std.all._, cats.syntax.all._ scala> "1" === 1 <console>:26: error: type mismatch; found : Int(1) required: String       "1" === 1               ^
  27. データ型と閉じた演算子という考え方に沿っている problem domain computer fp datatype operators
  28. see also Constraints Liberate, Liberties Constrain (video) Delphi にプリンタドライバが無かったので直に通信していた プリンタを変えると使えないプログラムになった
  29. see also Constraints Liberate, Liberties Constrain (video) 一度中間値を生成して、そこからプリンタに出力するべき
  30. see also Constraints Liberate, Liberties Constrain (video) 別の例としてはマインクラフトの爆発物 複数使うことでより強力な爆発を起こすことができる
  31. see also Constraints Liberate, Liberties Constrain (video) 一度こうなってしまうと合成しようが無い 副作用のメンタルイメージとなる
  32. see also Constraints Liberate, Liberties Constrain (video) よくある2 つの間違いは早すぎる具現化、 合成可能性を設計段階で考慮しないこと • concretizing too early • not designing for compositionality mistakes we make
  33. see also Constraints Liberate, Liberties Constrain (video) 具象的なシグネチャ 42億 * 42億通りの実装 def foo(a: Int): Int
  34. see also Constraints Liberate, Liberties Constrain (video) 型を変えることを許すことで、型を抽象化できる def foo[A](a: A): A
  35. see also Constraints Liberate, Liberties Constrain (video) あるレイヤーでの制約は別のレイヤーでの自由と力になる a constraint at one level leads to freedom and power at another level.
  36. finite set and arrow 有限集合と射 これは射の内部図式 internal diagram of an arrow
  37. finite set and arrow ドメインとコドメイン 有限集合の射は Scala では関数として書ける val favoriteBreakfast: Person => Breakfast = { case John => Eggs case Mary => Coffee case Sam => Coffee } domain codomain
  38. finite set and arrow これも射の内部図式 Sam が片想いになってる internal diagram of another arrow
  39. finite set and arrow ドメインとコドメインが同一の対象の射を自己準同型射と呼ぶ val favoritePerson: Person => Person = { case John => Mary case Mary => John case Sam => Sam } endomorphism: An arrow in which the domain and codomain are the same object.
  40. finite set and arrow 恒等射: ドメインとコドメインが同一の集合 A で、かつ A 内 の全ての a において f(a) = a であるもの identity arrow, 1A: An arrow, in which the domain and codomain are the same set A, and for each of a in A, f(a) = a scala> identity(John) res0: John.type = John
  41. finite set and arrow これまで見た射の外部図式 external diagrams of the arrows
  42. finite set and arrow 射の合成 composition of arrows
  43. finite set and arrow 射の合成 composition of arrows
  44. finite set and arrow f ∘ g は「f マル g」、または「f と g の合成射」と読む composition of arrows “f following g”, or “f of g”
  45. • objects: A, B, C • arrows: f: A B • identity arrows: 1A: A A • composition of arrows category 圏は対象、射、恒等射、射の合成から構成される これらのデータは単位元律と結合律を満たす必要がある • left identity law: If 1A: A A, g: A B, then g ∘ 1A = g • right identity law: If f: A B, 1B: B B, then 1A ∘ f = f • associative law: If f: A B, g: B C, h: C D, then
 h ∘ (g ∘ f) = (h ∘ g) ∘ f laws
  46. genericity 「抽象」という言葉を正確に定義できる 圏論から得られる概念にのみよる定義を抽象とする cat theory gives us tool to think in generic terms, and precise meaning to “abstract.” abstract (in cat theory): The definition uses only of the category theoric notions, rather than some additional information about about the objects and arrows.
  47. genericity 同型射は抽象概念の一例 逆射 g が定義できる射 f は同型射。A と B は同型。 cat theory gives us tool to think in generic terms, and precise meaning to “abstract.” abstract (in cat theory): uses only category theoric notions. for example: isomorphism: an arrow f: A ⇒ B is called an isomorphism, if there is an arrow g: B ⇒ A, for which g ∘ f = 1A and f ∘ g = 1B
  48. universal mapping property (UMP) 普遍写像性 (UMP; 普遍性) ある図式があるとき、別の図式を可換とする一意な x がある given a diagram abc, there exists a unique x that makes another diagram xyz commute.
  49. universal mapping property (UMP) 積の一意性: 任意の圏 C において、上の図が可換となる 一意の射 u: X ⇒ P が存在する。 uniqueness of products Given any category C, there exists a unique u: X ⇒ P, making the diagram commute.
  50. universal mapping property (UMP) 自由モノイド: 任意のモノイド N と任意の関数 f があるとき、 一意の準同型写像が存在する。 uniqueness of free monoids Given any monoid N and any function f there exists a unique monoid homomorphism f_hom: M(X) ⇒ N. f_hom(x • y) = f_hom(x) •’ f_hom(y), and f_hom(e) = e’
  51. universal mapping property (UMP) 積: (A, B) と同型 自由モノイド: List[A] と同型 free monoid ≅ List[A] product ≅ (A, B)
  52. monads モナドはフラクタルだ monads are fractals.
  53. monads List は ++ に関してモナドを形成する List forms a monad over ++. scala> List(List(1), List(2, 3), List(4)). foldLeft(List(): List[Int]) { _ ++ _ } res0: List[Int] = List(1, 2, 3, 4)
  54. monads Option は (_, _)._2 に関してモナドを形成する Option forms a monad over (_, _)_2. scala> (Some(None: Option[Int]): Option[Option[Int]]). foldLeft(None: Option[Int]) { (_, _)._2 } res20: Option[Int] = None scala> (Some(Some(1): Option[Int]): Option[Option[Int]]). foldLeft(None: Option[Int]) { (_, _)._2 } res21: Option[Int] = Some(1) scala> (None: Option[Option[Int]]). foldLeft(None: Option[Int]) { (_, _)._2 } res22: Option[Int] = None
  55. monads 両方のデータ型とも自己相似的な構造をフラットに潰すことが できる。 Both datatypes can crunch the self-similar structure into a flat one.
  56. monads どの 2項演算の上に join が実装されているかが、 そのモナドの意味論を決定する Both datatypes can crunch the self-similar structure into a flat one. What binary operation the flattening is implemented over determines the semantics of a monad.
  57. boxes (kinds) 箱について考えることができる cat theory gives us tool to think about boxes.
  58. boxes (kinds) 箱について考えることができる cat theory gives us tools to think about boxes.
  59. boxes (kinds) 箱について考えることができる cat theory gives us tools to think about boxes.
  60. boxes (kinds)
  61. Scala lets you abstract over a monadic datatype モナディックなデータ型に関して抽象なコードを書ける trait UserServices[F[_]] { this: UserRepos[F] =>   def userService: UserService = new UserService   class UserService {     import example.MonadSyntax._     def isFriends(user1: Long, user2: Long): F[Boolean] =       actM[F, Boolean] {         val a = userRepo.followers(user1).next         val b = userRepo.followers(user2).next         a.exists(_.id == user2) && b.exists(_.id == user1)       }   } } scala> val testService = new TestUserRepos with UserServices[Id] {} testService: TestUserRepos with UserServices[cats.Id] = ..
  62. Scala lets you abstract over a monadic datatype 例えば、ここでは XorT[Future, Error, ?] を渡している .. scala> val testService = new TestUserRepos with UserServices[Id] {} testService: TestUserRepos with UserServices[cats.Id] = .. scala> val service1 = {   import ExecutionContext.Implicits._   new UserRepos1 with UserServices[XorT[Future, Error, ?]] {} } service1: UserRepos1 with UserServices[[γ]cats.data.XorT[scala.concurrent.Future,Error,γ]] = $anon$1@ff10590
  63. thank you
  64. 猫番と独習 Scalaz • herding cats - http://eed3si9n.com/herding-cats/ • learning Scalaz - http://eed3si9n.com/learning-scalaz/
  65. Programming in Scala, 2nd ed Odersky, Spoon, Venners
  66. Learn You a Haskell for Great Good! Lipovača
  67. Functional Programming in Scala Chiusano and Rúnar
  68. Category Theory Awodey
  69. Scala in Depth Suereth
  70. Types and Programming Languages Pierce
  71. Conceptual Mathematics, 2nd ed Lawvere, Schanuel
Advertisement