Scala categorytheory


Published on

This was presented in Knolx session at Knoldus. This deals with basics of Category Theory and its relation with Scala.

Published in: Technology

Scala categorytheory

  1. 1. Category Theory In Scala Meetu Maltiar Principal Consultant Knoldus
  2. 2. AgendaCategory Theory the basicsCategory Theory in ScalaCode Examples
  3. 3. CategoryPierce defines Category as comprising of:● A collection of objects● A collection of arrows (often called morphisms)● Operations assigning to each arrow f an object dom f, itsdomain, and an object cod f, its codomain (f:A → B, wheredom f = A and cod f = B)
  4. 4. Category continued..A composition operator assigning to each pair of arrows f and g with cod f= dom g, a composite arrow g o f: dom f → cod g, satisfying the followingassociative law:for any arrows f:A → B, g:B → C and h:C → Dh o (g o f) = (h o g) o fFor each object A, an identity arrow idA: A → A satisfying the followingidentity law:for any arrow f:A → B, idB o f = f and f o idA = f
  5. 5. CategoryApples FruitBanana VegetableBrinjal f: A → B
  6. 6. Category CompositionApples Fruit LivingBanana Vegetable Non LivingBrinjal g o f: A → C
  7. 7. Translating to ScalaWe can define any function from a type A to type B as:A => B here we have an example or morphismFor any function val foo: A => B = //AnythingWe have type A as domain of function foo and type B as co-domainof function foo
  8. 8. Scala Category ExampleWe can define composition of arrows or functions in Scala withfollowing REPL examplescala> val f: Int => String = _.toStringf: Int => String = <function1>scala> val g: String => Int = _.lengthg: String => Int = <function1>scala> f compose gres3: String => String = <function1>
  9. 9. Scala category identity continuedIdentity law is a special version of a composition. Lets define function and playthem in REPL:scala> val foo: Int => String = _.toStringfoo: Int => String = <function1>scala> val idInt: Int => Int = identity(_: Int)idInt: Int => Int = <function1>scala> val idString: String => String = identity(_: String)idString: String => String = <function1>scala> idString compose foores4: Int => String = <function1>scala> foo compose idIntres5: Int => String = <function1>
  10. 10. Category theory and PLDo understanding Category Theory makes us understand PLs better?If we just do Enterprise software development and do not want to go beyondour comfort zone then answer is no.Category Theory provides uniform model of set theory, algebra, logic andcomputation.Many concepts of Category theory maps nicely to structures of PL.Categorical reasoning helps us to reason about programs. Some basicstructures in PL like product and sum types have their correspondences inCategory Theory.There is a strong correspondence between typed lambda calculus andcartesian closed categories
  11. 11. Properties of data type in CTConsider the category of Products of elements. Take for exampleof cartesian products from the category of sets.A cartesian product of two sets A and B is defined byA X B = {(a, b) | a belongs to A and b belongs to B}For example if A = {1, 2} and B = {A, B}A X B = {(1, A), (1, B), (2, A), (2, B)}So here we have tuples or Pairs as objects in a Category
  12. 12. Properties of data type in CT ..But what will be morphisms?In case of products, the applicable arrows (or morphisms)are the projection functions:π1: A X B → Aπ1: A X B → B
  13. 13. Properties of data type in CT ..Now if we draw a Category diagram with C as a product type wehave two functions as projection functions:1. f: C → A2. g: C → Band the product function is represented by: C → A X B It is definedby:<F, G>(x) = (f(x), g(x))
  14. 14. Diagram of CT C f g ! [f,g]A AXB B π1 π2
  15. 15. Diagram of CTFor every pair of vertices X and Y, all paths in the diagram from Xto Y are equal in the sense that each path forms an arrow andthese arrows are equal in categoryFor example the path from C to A is: <f,g> and π1 thereforecomposition gives us:π1 o <f,g> = fAlso path from C to B gives us: <f,g> and π2π2 o <f,g> = g
  16. 16. Scala CT exampleLets now see how the laws of commutativity maps to Scala.As a programmer we use the projection functions (_1 and _2) inScala Tuple2 on a regular basisIn the CT diagram we will see that we get additional insights inabstraction and help understand mathematical properties of howcartesian product of sets map translates to composition offunctions
  17. 17. Scala CT example...scala> val ip = (10, "meetu")ip: (Int, java.lang.String) = (10,meetu)scala> val pi1: ((Int, String)) => Int = (p => p._1)pi1: ((Int, String)) => Int = <function1>scala> val pi2: ((Int, String)) => String = (p => p._2)pi2: ((Int, String)) => String = <function1>scala> val f: Int => Int = (_ * 2)f: Int => Int = <function1>scala> val g: Int => String = _.toStringg: Int => String = <function1>scala> val `<f, g>`: Int => (Int, String) = (x => (f(x), g(x)))<f, g>: Int => (Int, String) = <function1>scala> pi1 compose `<f, g>`res0: Int => Int = <function1>scala> pi2 compose `<f, g>`res1: Int => String = <function1>
  18. 18. Scala CT exampleSo we can claim from the commutativity of the diagram that:pi1 compose `<f, g>` is type wise equal to fpi2 compose `<f, g>` is type wise equal to gCategory theory says that morphism between C and A X B isunique and that A X B is defined upto isomorphism.Uniqueness is denoted by ! In diagram. This makes sense as wellbecause a pair can be unique
  19. 19. Interface driven modelingCategory Theory maps very closely to PL in the sense that itfocuses on arrows rather than objects corresponding to InterfacesPierce: CT typically “abstracts away from elements, treatingobjects as black boxes with unimagined internal structure andfocusing attention on the properties of arrows between objects”Learning CT enriches both CT and PL. For example if we knowwhat a Functor is in CT then we can easily make it generic enoughso that it can interact with other Functors
  20. 20. Thinking GenericallyCT talks about objects and morphisms and how arrows compose.A special kind of morphism is identity function in programming.It is 0 in addition and 1 in multiplicationCT generalizes this concept by using same vocabulary (morphism)to denote both stuff that does some operations and those that dontFor every object X, there exists a morphism idX: X → X calledidentity morphism on X, such that for every morphism f: A → B wehave:IdB o f = f = f o idA (used in monoids)
  21. 21. DualityWe have seen example of SumTypes for Product. If we look at theCT diagram of Sum compared to Product we see that arrows arereversed.This is called a dual in CT. In Scala we model it by a Union Typelike Either where value of SumType comes either from left or right
  22. 22. Whats NextFunctorsMonadsScalazResources:1. Debasish Ghosh blog “Does Category Theory Makes you ABetter Programmer”2. Heikos blog on Category Theory3. Runar video on Scalaz