82
Thinking in Cats eugene yokota (@eed3si9n) Typesafe March 2016, ScalaMatsuri

Thinking in Cats

Embed Size (px)

Citation preview

Page 1: Thinking in Cats

Thinking in Catseugene yokota (@eed3si9n)

Typesafe March 2016, ScalaMatsuri

Page 2: Thinking in Cats

文字数制限あり。折りたたみやエンコーディングは無し。

• Reactive Platform team at Typesafe

• a commercial development platform for pros

• tech lead of

Typesafe で仕事しています

About me

Page 3: Thinking in Cats

文字数制限あり。折りたたみやエンコーディングは無し。 Cats というライブラリの話

Cats

Page 4: Thinking in Cats

Cats は Scala プログラミング言語で関数型プログラミングをするための抽象化を提供するライブラリ

Cats is a library to provide abstraction for functional programming in the Scala programming language.

Page 5: Thinking in Cats

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).

Page 6: Thinking in Cats

文字数制限あり。折りたたみやエンコーディングは無し。

hard cats

soft cats

2種類の猫

Page 7: Thinking in Cats

software doesn’t exist in a vacuumソフトウェアは真空状態に存在するものではない

Page 8: Thinking in Cats

software doesn’t exist in a vacuum水、酸素、光、土壌など

• water • oxygen • light • soil (nutrients, pH)

Page 9: Thinking in Cats

software doesn’t exist in a vacuum継続的にメンテ(進化)するための開発リソース、セオリー、 コミュニティ、周辺プラグイン、ドキュメンテーション

• development resource tomaintain/evolve the system

• underlying theory • user community • surrounding plugins/libraries • documentation

Page 10: Thinking in Cats
Page 11: Thinking in Cats
Page 12: Thinking in Cats

60 contributors + 547 pull requests in an year.

コントリビュータは色んな所から集まってきてる pull req も一年で 547 本と活発

Page 13: Thinking in Cats

d6 (also known as non, Erik)d6 の人柄みたいなのが、ライブラリの方針に反映されている

Page 14: Thinking in Cats

motivationsとっつきやすさ、モジュール性、ドキュメンテーション、 効率性

•Approachability •Modularity •Documentation •Efficiency

Page 15: Thinking in Cats

see also Principles for Modular, Functional, Approachable Libraries (video, slides)

goals

関数型、安全、高速、ドキュメントが整備されている、 モジュラー、慣用的、実用的、協調、友好的

•Functional •Safe •Fast •Documented •Modular •Idiomatic •Pragmatic •Collaborative •Welcoming

Page 16: Thinking in Cats

see also Principles for Modular, Functional, Approachable Libraries (video, slides)

goals

Scala で関数型プログラムをおこなう障壁を取り除く

“Remove barriers to doing functional programming in Scala.”

Page 17: Thinking in Cats

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)

Page 18: Thinking in Cats

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

Page 19: Thinking in Cats
Page 20: Thinking in Cats

プログラマが行う作業: 問題ドメインをモデル化して、 コンピュータで実行させる

problem domain

model

computer

what we do

Page 21: Thinking in Cats

fp では問題ドメインから時系列を抜いて、 データ型と演算子に分け、それを計算機で評価する

problem domain computer

fp

datatype

operators

Page 22: Thinking in Cats

合成可能性、論理的な推論可能性

problem domain computer

fp

datatype

operators

•composability •reasonable

Page 23: Thinking in Cats

演算子がデータ型の関係性を記述する 型クラスによる抽象化

problem domain computer

fp

datatype

operators

•composability •reasonable

•typeclasses

Page 24: Thinking in Cats

評価器としてのインタプリタ 制御された作用、高性能化など

problem domain interpretor

fp

datatype

operatorsevaluate

•controlled effects

Page 25: Thinking in Cats

「型システムとは、(中略) プログラムがある種の振る舞いを起こさないことを保証する構文的手法である。」TAPL から

soundness

“A type system is a syntactic method for automatically checking the absence of certain erroneous behaviors…”

Page 26: Thinking in Cats

健全性: 論証が妥当であり、かつ前提の全てが真であること

soundness

•argument is valid (all cups are green; Socrates is a cup; therefore, Socrates is green.)

P→Q •all premise is true

P ~ true

Page 27: Thinking in Cats

これはコンパイルが通るべきではない

soundness?

scala> "1" == 1 res0: Boolean = false

this should not compile

Page 28: Thinking in Cats

等価性はこのように定義されるべき

equality

trait Eq[A] {   def equal(a1: A, a2: A): Boolean }

Page 29: Thinking in Cats

Cats での等価性

equalityscala> import cats._, cats.std.all._, cats.syntax.all._ scala> "1" === 1 <console>:26: error: type mismatch; found : Int(1) required: String       "1" === 1               ^

Page 30: Thinking in Cats

データ型と閉じた演算子という考え方に沿っている

problem domain computer

fp

datatype

operators

Page 31: Thinking in Cats
Page 32: Thinking in Cats

see also Constraints Liberate, Liberties Constrain (video)

Delphi にプリンタドライバが無かったので直に通信していた プリンタを変えると使えないプログラムになった

Page 33: Thinking in Cats

see also Constraints Liberate, Liberties Constrain (video)

一度中間値を生成して、そこからプリンタに出力するべき

Page 34: Thinking in Cats

see also Constraints Liberate, Liberties Constrain (video)

別の例としてはマインクラフトの爆発物 複数使うことでより強力な爆発を起こすことができる

Page 35: Thinking in Cats

see also Constraints Liberate, Liberties Constrain (video)

一度こうなってしまうと合成しようが無い 副作用のメンタルイメージとなる

Page 36: Thinking in Cats

see also Constraints Liberate, Liberties Constrain (video)

よくある2 つの間違いは早すぎる具現化、 合成可能性を設計段階で考慮しないこと

• concretizing too early • not designing for compositionality

mistakes we make

Page 37: Thinking in Cats

see also Constraints Liberate, Liberties Constrain (video)

具象的なシグネチャ 42億 * 42億通りの実装

def foo(a: Int): Int

Page 38: Thinking in Cats

see also Constraints Liberate, Liberties Constrain (video)

型を変えることを許すことで、型を抽象化できる

def foo[A](a: A): A

Page 39: Thinking in Cats

see also Constraints Liberate, Liberties Constrain (video)

あるレイヤーでの制約は別のレイヤーでの自由と力になる

a constraint at one level leads to freedom and power at another level.

Page 40: Thinking in Cats
Page 41: Thinking in Cats

finite set and arrow

有限集合と射 これは射の内部図式

internal diagram of an arrow

Page 42: Thinking in Cats

finite set and arrow

ドメインとコドメイン 有限集合の射は Scala では関数として書ける

val favoriteBreakfast: Person => Breakfast = { case John => Eggs case Mary => Coffee case Sam => Coffee }

domain codomain

Page 43: Thinking in Cats

finite set and arrow

これも射の内部図式 Sam が片想いになってる

internal diagram of another arrow

Page 44: Thinking in Cats

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.

Page 45: Thinking in Cats

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

Page 46: Thinking in Cats

finite set and arrow

これまで見た射の外部図式

external diagrams of the arrows

Page 47: Thinking in Cats

finite set and arrow

射の合成

composition of arrows

Page 48: Thinking in Cats

finite set and arrow

射の合成

composition of arrows

Page 49: Thinking in Cats

finite set and arrow

f ∘ g は「f マル g」、または「f と g の合成射」と読む

composition of arrows

“f following g”, or “f of g”

Page 50: Thinking in Cats

• 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

Page 51: Thinking in Cats
Page 52: Thinking in Cats

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.

Page 53: Thinking in Cats

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

Page 54: Thinking in Cats

universal mapping property (UMP)

普遍写像性 (UMP; 普遍性) ある図式があるとき、別の図式を可換とする一意な x がある

given a diagram abc, there exists a unique x that makes another diagram xyz commute.

Page 55: Thinking in Cats

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.

Page 56: Thinking in Cats

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’

Page 57: Thinking in Cats

universal mapping property (UMP)

積: (A, B) と同型 自由モノイド: List[A] と同型

free monoid ≅ List[A]

product ≅ (A, B)

Page 58: Thinking in Cats
Page 59: Thinking in Cats

monads

モナドはフラクタルだ

monads are fractals.

Page 60: Thinking in Cats

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)

Page 61: Thinking in Cats

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

Page 62: Thinking in Cats

monads

両方のデータ型とも自己相似的な構造をフラットに潰すことができる。

Both datatypes can crunch the self-similar structure into a flat one.

Page 63: Thinking in Cats

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.

Page 64: Thinking in Cats
Page 65: Thinking in Cats
Page 66: Thinking in Cats

boxes (kinds)

箱について考えることができる

cat theory gives us tool to think about boxes.

Page 67: Thinking in Cats

boxes (kinds)

箱について考えることができる

cat theory gives us tools to think about boxes.

Page 68: Thinking in Cats

boxes (kinds)

箱について考えることができる

cat theory gives us tools to think about boxes.

Page 69: Thinking in Cats

boxes (kinds)

Page 70: Thinking in Cats
Page 71: Thinking in Cats
Page 72: Thinking in Cats

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] = ..

Page 73: Thinking in Cats

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

Page 74: Thinking in Cats

thank you

Page 75: Thinking in Cats

猫番と独習 Scalaz

• herding cats - http://eed3si9n.com/herding-cats/• learning Scalaz - http://eed3si9n.com/learning-scalaz/

Page 76: Thinking in Cats

Programming in Scala, 2nd ed Odersky, Spoon, Venners

Page 77: Thinking in Cats

Learn You a Haskell for Great Good! Lipovača

Page 78: Thinking in Cats

Functional Programming in Scala Chiusano and Rúnar

Page 79: Thinking in Cats

Category Theory Awodey

Page 80: Thinking in Cats

Scala in Depth Suereth

Page 81: Thinking in Cats

Types and Programming Languages Pierce

Page 82: Thinking in Cats

Conceptual Mathematics, 2nd ed Lawvere, Schanuel