Upgrade to Pro — share decks privately, control downloads, hide ads and more …

shapeless - exploring generic programming in Scala

shapeless - exploring generic programming in Scala

Miles Sabin

March 13, 2012
Tweet

Other Decks in Programming

Transcript

  1. shapeless – exploring generic programming in Scala Miles Sabin [email protected]

    http://underscoreconsulting.com/ http://uk.linkedin.com/in/milessabin http://twitter.com/milessabin
  2. Outline • History • What is an HList? • Polymorphic

    function values • Type-level functions • Type- and value-level recursion • Putting the pieces together • Find out more ...
  3. History • Scrap your boilerplate with class in Scala •

    Polymorphic function values • Functional dependencies • shapeless • Main goal – explore abstractions over shapes richer than can be captured by traditional parametric polymorphism (even with higher-kinded types) • Initial objective – an HList which supports map
  4. What is an HList? • HLists combine the characteristics of

    both lists and tuples • Tuples are fixed length sequences of elements of distinct types • Lists are variable length sequences of elements all of the same type • HLists are variable length sequences of elements of distinct types • Code ...
  5. Polymorphic function values • The first piece of the picture

    If we're going to map over an HList we need “functions” which can be applied to all of its element types • Natural transformations? F[T] => G[T] Not general enough ... only gets us to KLists • SYB gives us the clue Represent polymorphic function values via type classes and instances (taking in singleton and dependent types on the way) • Code ...
  6. Type-level functions • Consider the last operation on an HList

    • How do we specify its signature? Int :: String :: Boolean :: HNil => Boolean • We need some way of encoding the relationship between the type of the whole HList and the type of its last element • Implicits and dependent types to the rescue • Code ...
  7. Type- and value-level recursion • What we just saw is

    an instance of a general pattern • Type-level recursion “computes” the result type • Value-level recursion computes the result value • We do the two in tandem • Let's look at another slightly more complex example – reverse • Code ...
  8. Putting the pieces together • Now we're ready to map

    that HShit! • This time our type-level recursion will • Compute the result type – as before • Select the appropriate type-specific case of our polymorphic function for each element as we go • Code ...
  9. Find out more ... • Fork it! http://github.com/milessabin/shapeless • Mailing

    list http://groups.google.com/group/shapeless-dev • Articles http://chuusai.com/blog
  10. shapeless – exploring generic programming in Scala Miles Sabin [email protected]

    http://underscoreconsulting.com/ http://uk.linkedin.com/in/milessabin http://twitter.com/milessabin