Scala Types of Types @ Lambda Days

Download Scala Types of Types @ Lambda Days

Post on 10-May-2015

2.113 views

Category:

Technology

1 download

Embed Size (px)

DESCRIPTION

Talk from LambdaDays 2014 in Krakow. The talk focuses on some of Scala's more prominent types. Video available here: https://vimeo.com/92620078

TRANSCRIPT

<ul><li>1.ScalasTypes of Types bg = game @ http://www.swordandsworcery.com/Konrad 'ktoso' MalawskiLambda Days 2014 @ Krakw</li></ul> <p>2. _@Konrad `@ktosopl` Malawskigeecon.orgJava.pl / KrakowScala.plsckrk.com / meetup.com/Paper-Cup @ LondonGDGKrakow.pl meetup.com/Lambda-Lounge-Krakow 3. Types 4. TypesImplementation is an implementation detail.~ ktoso 5. Types in Scala 6. Types in Scala 7. Types in Scala Types are:!staticclass Robot! class Human ! ! val human: Human = new Human! val roman: Human = new Robot! ! ! error: type mismatch;! ! found : Robot! ! required: Human! ! val robot: Human = new Robot! !^ 8. Types in Scala Types are:!static strongvar two = 2! two = "two"! !error: type mismatch;! found : String("two")! required: Int! two = "two"! ^ 9. Types in Scala Types are:!static strong inferred !val n = 2! n.getClass.toString == "int"! ! ! !class Human! !val p = new Human!p.getClass.toString == "class Human" 10. Types in Scala Types are:! val n: Int = 2!static strong inferred annotated after : ! !! def add(a: Int, b: Int): Int! 11. Types with Traits 12. Types with Traits Traits are:!interfaces !implementation: trait HasName { ! def name: String! }! ! !class Human extends HasName {! def name = ""! } class Human(val name: String) ! extends HasName! 13. Types with Traits Traits are:!interfaces with implementation !trait HasName { def name = "name" }! !object Human extends HasName! !Human.name == "name"! 14. Types with Traits Traits are:!interfaces with implementation can be mixed intrait Robot! trait Humanoid! trait Lasers! !object X extends Robot ! with Humanoid! with Lasers! !Multiple inheritance panic?! 15. Type linearizationtrait Robot extends Lasers! trait Humanoid! trait Lasersobject X extends Robot ! with Humanoid! with Lasers// type linearization:! X Robot Humanoid Lasers // reverse! X Lasers Humanoid Robot! ! ! // expand! X Lasers Humanoid Robot Lasers // right-keep-unique! X Lasers Humanoid Robot Lasers! X Humanoid Robot Lasers // add common! X Humanoid Robot Lasers Object Any 16. Type linearizationtrait Robot extends Lasers! trait Humanoid! trait Lasersobject X extends Robot ! with Humanoid! with Lasers// dont trust me, trust the compiler:! import scala.reflect.runtime.universe._! typeOf[X.type].baseClasses.map(_.name).mkString( extends ")! !// output:! X extends Humanoid ! extends Robot extends Lasers ! extends Object extends Any! 17. Type linearization reordered slightly trait Robot extends Lasers! trait Humanoid! trait Lasersobject X extends Humanoid! with Lasers! with Robot// type linearization:! X Humanoid Lasers Robot // reverse! X Robot Lasers Humanoid! ! ! // expand! X Robot Lasers Lasers Humanoid // right-keep-unique! X Robot Lasers Lasers Humanoid! X Robot Lasers Humanoid // add common! X Robot Lasers Humanoid Object Any 18. Type linearizationtrait Robot extends Lasers! trait Humanoid! trait Lasersobject X extends Humanoid! with Lasers! with Robot// dont trust me, trust the compiler:! import scala.reflect.runtime.universe._! typeOf[X.type].baseClasses.map(_.name).mkString( extends ")! !// output:! X extends Robot ! extends Lasers extends Humanoid! extends Object extends Any! 19. Type Renement 20. Type Renement trait Human! trait Robotval human: Human = new Human {}! val roman: Human = new Robot! 21. Type Renement trait Human! trait Robotval human: Human = new Human {}! val roman: Human = new Robot with Human!plain trait composition type renementWaaah! Its a robot with human traits! 22. Compound Types 23. Compound Types areintersections of types ! ! ! ! !trait def }! trait def }!Openable {! open()! Closable {! close()! 24. Compound Types areintersections !! ! ! !open()trait def }! trait def }!Openable {! open()! Closable {! close()!close() 25. Compound Types areintersections !trait def }! trait def }!Openable {! open()! Closable {! close()!! ! ! def openAndClose(it: Openable with Closable) {! it.open() ! !it.close()! } 26. Compound Types areintersections !trait def }! trait def }!Openable {! open()! Closable {! close()!! ! ! def openAndClose(it: Openable with Closable) {! it.open() ! !it.close()! } 27. Compound Typesthis.typetrait def }! trait def }!Openable {! open(): this.type! Closable {! close()!! ! ! def openAndClose(it: Openable with Closable) =! !it.open().close() 28. !Type Parameters 29. !Type Parameters[Type Variance] 30. !Type Parameters[Type Variance]: 31. Type Parameters type constructorclass C[T] type parameter 32. Type Varianceclass C[T] // in-variant! class C[+T] // co-variant! class C[-T] // contra-variant! 33. Type Bounds (still variance)class Parent! class Bottom extends Parent! !Type Bounds!Parent &gt;: Bottom Bottom // structural type! type Closeable = {! def close()! } 39. Structural Types Kinda like duck typingdef send(msg: String, box: {def receive(a: String)}) =! box receive msgstructural type 40. Structural Types type alias type MailBoxLike = { ! def receive(a: String)! } def send(msg: String, box: MailboxLike) =! box receive msg 41. Structural Typestype MailBoxLike = { ! def receive(a: String)! } def send(msg: String, box: MailboxLike) =! box receive msg object Home { def receive(a: String) = ??? }! object Work { def receive(a: String) = ??? } send("hello at home", Home)! send("hello at work", Work) 42. Type Member 43. Type Member Same goal asType Parameter if List was using Type Params trait StringList! extends List[String]=&gt;trait StringList ! extends List {! type A = String! }if List was using Type Members 44. Type Member + Type Bound Same as + / - variance trait List {! type A! }=&gt;trait NumbersList extends List {! type A string` ! extends Builder[Array[Byte], String] {! ! def make(in: Array[Byte]): String = new String(in)! }! 48. Type Alias From Type Parameter to Type Memberstrait Builder[From, To]=&gt;trait Builder {! type From! type To! def make(in: From): To! } 49. Type Aliastrait Builder { type From; type To; def make(in: From): To }! trait StringBuilder extends Builder {! type To = String! } trait FromBytesBuilder extends Builder {! type From = Array[Byte]! } object `bytes -&gt; string` extends Builder! with FromBytesBuilder! with StringBuilder {! ! def make(in: From): To = new String(in)! }! 50. Type Aliastrait Builder { type From; type To; def make(in: From): To }!object `bytes -&gt; string` extends Builder {! type From = Array[Bytes]! type To = String! !def make(in: From): To = new String(in)! }! 51. Phantom Types 52. Phantom TypesPhantom Types are never actually instanciated.Exactly!uhm where are they? 53. Phantom Types Marker traits: sealed trait DoorState! final class Open extends DoorState! final class Closed extends DoorState! 54. Phantom Types Marker traits: sealed trait DoorState! final class Open extends DoorState! final class Closed extends DoorState!trait Door[State : State : State *) -&gt; *! !This is a type constructor that takes type constructor(s): ! a higher-kinded type 69. Higher Kinded Typesimport scala.language.higherKinds! !takes Type Constructortrait Functor [F[_]] {! def map[A,B] (fn: A =&gt; B)(fa: F[A]): F[B]! } 70. Higher Kinded Types import scala.language.higherKinds! !trait Functor [F[_]] {! def map[A,B] (fn: A =&gt; B)(fa: F[A]): F[B]! }trait Functor [List] {! def map[Int,String] (fn: Int =&gt; String)! (fa: List[Int]): List[String]! } 71. Higher Kinded Types import scala.language.higherKinds! !trait Functor [F[_]] {! def map[A,B] (fn: A =&gt; B)(fa: F[A]): F[B]! }val funct = new Functor[List] {! def map[String, Int] ! (f: String =&gt; Int)! (fa: List[String])! : List[Int] = fa map f // cheating ;-)! } 72. Higher Kinded Types import scala.language.higherKinds! !trait Functor [F[_]] {! def map[A,B] (fn: A =&gt; B)(fa: F[A]): F[B]! } val funct = new Functor[List] {! def map[String, Int] ! (f: String =&gt; Int)! (fa: List[String]): List[Int] = ! ! ! !!! fa map f // cheating ;-)! } val f: Int =&gt; String = _.toString! funct.map(f)(List(1, 2)) == List("1", "2")! 73. Power up: Ad-Hoc Polymorphism trait Container[M[_]] { ! def put[A](x: A): M[A]; def get[A](m: M[A]): A ! }! implicit val listContainer = new Container[List] { ! def put[A](x: A) = List(x)! def get[A](m: List[A]) = m.head ! }! !implicit val optionContainer = new Container[Some] {! def put[A](x: A) = Some(x);! def get[A](m: Some[A]) = m.get ! }! 74. Power up: Ad-Hoc Polymorphism trait Container[M[_]] { ! def put[A](x: A): M[A]; def get[A](m: M[A]): A ! }!def tupleize[M[_]: Container, A, B]! (fst: M[A], snd: M[B]) ! (implicit c: Container[M]): M[(A, B)] = c.put(c.get(fst), c.get(snd)) tupleize(Some(1), Some(2))! Some((1,2)): Some[(Int, Int)]! !tupleize(List(1), List(2))! List((1,2)): List[(Int, String)]! 75. Power up: Ad-Hoc Polymorphism trait Container[M[_]] { ! def put[A](x: A): M[A]; def get[A](m: M[A]): A ! }!def tupleize[M[_]: Container, A, B]! (fst: M[A], snd: M[B]) ! (implicit c: Container[M]): M[(A, B)] = c.put(c.get(fst), c.get(snd)) tupleize(Some(1), Some(2))! Some((1,2)): Some[(Int, Int)]! !tupleize(List(1), List(2))! List((1,2)): List[(Int, String)]! 76. Type Class 77. Type ClassA.K.A. ad-hoc polymorphism 78. Type ClassA.K.A. More pattern, than type 79. Type ClassA.K.A. Stay in this room 80. Type ClassA.K.A. Stay in this roomJerzy has an entire talk about them 81. Type Class// no type classes yet! trait Writeable[Out] {! def write: Out! }! !case class Num(a: Int, b: Int) extends Writeable[Json] {! def write = Json.toJson(this)! }! 82. Type Class trait Writes[In, Out] { def write(in: In): Out! }! ! !Separated what from whotrait Writeable[Self] { def writeAs[Out]()! (implicit writes: Writes[Self, Out]): Out =! ! ! ! ! writes write this! }! ! ! ! implicit val jsonNum = Writes[Num, Json] {! ! def write(n: Num) = Json.toJson(n)! ! }! !case class Num(a: Int) extends Writeable[Num] 83. Type Class trait Writes[In, Out] { def write(in: In): Out! }! ! !trait Writeable[Self] { def writeAs[Out]()! (implicit writes: Writes[Self, Out]): Out =! ! ! ! ! writes write this! }!Implicit parameter! ! ! implicit val jsonNum = Writes[Num, Json] {! ! def write(n: Num) = Json.toJson(n)! ! }! !Implicit valuecase class Num(a: Int) extends Writeable[Num] 84. Type Class implicit val jsonNum = Writes[Num, Json] { def (n1: Num, n2: Num) = n1.a &lt; n1.! }! !case class Num(a: Int) extends Writeable[Num] 85. Type Class implicit val jsonNum = Writes[Num, Json] { def (n1: Num, n2: Num) = n1.a &lt; n1.! }! !case class Num(a: Int) extends Writeable[Num]you write: val jsonNum = Num(12).writeAs[Json]()! 86. Type Class implicit val jsonNum = Writes[Num, Json] { def (n1: Num, n2: Num) = n1.a &lt; n1.! }! !case class Num(a: Int) extends Writeable[Num]you write: val jsonNum = Num(12).writeAs[Json]()!compiler does: val jsonNum = Num(12).writeAs[Json]()(jsonNum)! 87. Links &amp; Kudos 88. ktoso/scala-types-of-types @ github12444 words and growing 89. Other Types of Typestype annotationcase classtype projection unied type systemvalue classself recursive typebottom typestype classtype constructor type varianceuniversal traitspecialized typetraitsself type annotationdynamic typetype renementsphantom typeexistential typetype aliasstructural typetype lambdaabstract type member path dependent type algebraic data type 90. Links and Kudos http://docs.scala-lang.org/ ! http://ktoso.github.io/scala-types-of-types/! ! http://blog.echo.sh/post/68636331334/experimenting-with-peano-numbers-on-scalas-type-system-1! http://stackoverow.com/questions/6246719/what-is-a-higher-kinded-type-in-scala! http://twitter.github.io/scala_school/advanced-types.html! https://github.com/earldouglas/scala-scratchpad/tree/master/type-lambdas! http://www.scala-lang.org/old/node/136! http://eed3si9n.com/learning-scalaz/polymorphism.html! ! ! 91. Dzikuj! Thank you! (guess type occurrences)K.Malawski @ ebay.com Konrad.Malwski @ geecon.org t: ktosopl / g: ktoso blog: project13.plLambda Days 2014 @ Krakw </p>