SlideShare a Scribd company logo
Introduction to Type Level
Programming
Or: How to blame the Scala compiler when nothing works
Yuval Itzchakov
13/02/2018
YuvalItzchakov
2
• Developer @ Clicktale for the past 3 years
• Previously developer @ IDF (8200)
@yuvalitzchakov
https://stackoverflow.com/users/1870803/yuval-itzchakov
h http://asyncified.io
https://fpchat-invite.herokuapp.com/ (yuval.Itzchakov)
Agenda
3
• Type Level Programming In a Nutshell
• Show[A]
• Implicits
• Typeclass Pattern
• Generic Derivation
TypeLevelProgramming
4
• The compiler is the verification tool for our program.
• Can we make it do more?
• How about generating types at compile time for us?
TypeLevelProgramming
5
Giuseppe Peano
Show[A]
6
trait Show[A] {
def show(a: A): String
}
• Defines a string representation for a type.
• Allows us to define custom representations for closed types.
PrintingaArray[Byte]
7
We want to print a byte array:
val bytes = Array[Byte](30, 57, 92)
println(bytes) // [B@6615435c
On the other hand, given a Show instance:
val showBytes = new Show[Array[Byte]] {
override def show(arr: Array[Byte]): String = arr.map("%02X" format _).mkString(",")
}
println(showBytes.show(bytes)) // 1E,39,5C
Wherewe’regoing
8
Given any case class:
case class Person(firstName: String, lastName: String, age: Int)
We’ll be able to automatically derive a Show instance for it:
val p = Person("yuval", "itzchakov", 30)
val personShower: Show[Person] = ??? // Magic
personShower.show(p) // yuval, itzchakov, 30
Startingsimple
9
Let’s see how we define Show instances for primitive types
Nice,butalittleugly
10
• Can we do better?
• YES! IMPLICITS!
implicit val intEncoder: Show[Int] = new Show[Int] {
override def show(i: Int): String = i.toString
}
Implicits
11
• An implicit parameter is used to summon the Show[A] trait.
• Scala compiler searches for a suitable implicit in scope.
• If found, the compiler fills in the right instance at compile
time.
• Implicit resolution works recursively.
TypeclassPattern
13
• Defining common behavior for types, without
inheritance.
• Trait definition with a polymorphic type
• Concrete implicit instances
• Originated in Haskell
• A form of ad-hoc polymorphism (A.K.A
overloading)
TypeclassDefinition
14
Any method requiring the type class, asks for it implicitly from the
compiler:
def log[A](a: A)(implicit shower: Show[A]): String = {
shower.show(a)
}
println(log(10)) // log(10)(intEncoder) -> 10
TypeclassPattern
15
The implicit value must be in scope, otherwise:
Error:(45, 19) could not find implicit value for parameter
show: Show[Int]
println(log(10))
TypeclassPattern
16
Who uses the typeclass pattern?
• Scala Collections – Ordering[A], CanBuildFrom[A]
• Circe – Encoder[A] / Decoder[A]
• Avro4S – ToRecord[A] / FromRecord[A]
• Cats / Scalaz – Functor[A], Monoid[A], Applicative[A]
• Many more!
Canwedo better?
17
• Can the compiler resolve, based on existing primitive implicits,
more complex types?
• How about a Tuple2 of primitives?
type Person = (String, (String, Int))
type Person = Tuple2[String, Tuple2[String, Int]]
18
RecursiveImplicitResolution
19
type Person = Tuple2[String, Tuple2[String, Int]]
implicit def tupleShow[Head, Tail](
implicit
headShow: Show[Head],
tailShow: Show[Tail])
Show[String]
Do I have an implicit for Tuple2?
Show[Tuple[String, Int]]
Recurse
RecursiveImplicitResolution
20
type Person = Tuple2[String, Tuple2[String, Int]]
Do I have an implicit for Tuple2?
implicit def tupleShow[Head, Tail](
implicit
headShow: Show[Head],
tailShow: Show[Tail])
Show[String]
Show[Int]
But…
21
• In real life, we usually don’t encode types as tuples
• And we want to abstract over arity (Tuple3, Tuple4,
TupleN)
• We really want to encode with case classes
• Can we do that?
Whatarecaseclasses,really?
22
• Named tuples on steroids.
• Compiler generated method implementations.
• Can be of any arity ( >= Scala 2.11).
• How do we deal with that? Can they be represented
generically?
Yes,wecan!
23
• Using HList (Heterogenous List)
• Heterogenous for holding different types
val hlist: ::[String, ::[Boolean, ::[Int, HNil]]] =
"Scala-IL" :: true :: 42 :: HNil
val meetUp: String = hlist.head // “Scala-IL”
val isItAwesome: Boolean = hlist.tail.head // true
24
shapeless
25
“shapeless is a type class and dependent type based generic
programming library for Scala” (from GitHub).
• Provides us with a vast amount of building blocks for TLP
• Consumed by many popular libraries in the ecosystem:
• circe
• avro4s
• scodec
• spray
Interesting..
26
• Can we rework our example to derive a Show[A] instance
for any case class using HList?
• Let’s try!
Evolution
27
type Person = Tuple2[String, Tuple2[String, Int]]
case class Person(firstName: String, lastName: String, age: Int)
type Person =
shapeless.::[String, shapeless.::[String, shapeless.::[Int, HNil]]]
28Confidential
• Implicit resolution error messages
• Use tek/splain (https://github.com/tek/splain)
• Things can become… complex
def collect[HL <: HList,
RL <: HList,
KL <: HList,
ZL <: HList]
(implicit
iso: LabelledGeneric.Aux[C, HL] ,
annot: Annotations.Aux[A, C, RL] ,
keys: Keys.Aux[HL, KL] ,
zip: Zip.Aux[KL :: RL :: HNil, ZL] ,
leftFolder: LeftFolder.Aux[ZL, B, Collector.type, B]): B
Limitations
29Confidential
• Compile times – Take care of your implicit scope!
Limitations
30Confidential
• You’re probably using it already
• Building codecs (JSON, Avro, XML, or custom)
• Abstracting over arity
• Updating nested data structured (lenses)
• Type safe casts (when you really must)
Where TLP Meets You
31Confidential
• The Scala compiler is a powerful tool.
• We can leverage it to do amazing things, like generically derive
types for us.
• shapeless is a powerful building block in that process.
• Mixing it all together, type level programming becomes
immensely powerful.
Conclusion
32Confidential
https://github.com/YuvalItzchakov/tlp-underscore
Presentation Code
33Confidential
• The Type Astronaut’s Guide to Shapeless (Dave Gurnell)
https://github.com/davegurnell/shapeless-guide
• Daniel Spiewak – High Wizardy in the Land Of Scala
https://vimeo.com/28793245
• Aaron Levin – Mastering Typeclass Induction
https://www.youtube.com/watch?v=Nm4OIhjjA2o
• Li Haoyi - Implicit Design Patterns in Scala
http://www.lihaoyi.com/post/ImplicitDesignPatternsinScala.html
Resources
Thank you for listening!
Questions?

More Related Content

What's hot

Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Igalia
 
CocoaConf DC - Automate with Swift - Tony Ingraldi
CocoaConf DC -  Automate with Swift - Tony IngraldiCocoaConf DC -  Automate with Swift - Tony Ingraldi
CocoaConf DC - Automate with Swift - Tony Ingraldi
Tony Ingraldi
 
Why Scala?
Why Scala?Why Scala?
Why Scala?
Alex Payne
 
A Static Type Analyzer of Untyped Ruby Code for Ruby 3
A Static Type Analyzer of Untyped Ruby Code for Ruby 3A Static Type Analyzer of Untyped Ruby Code for Ruby 3
A Static Type Analyzer of Untyped Ruby Code for Ruby 3
mametter
 
groovy & grails - lecture 1
groovy & grails - lecture 1groovy & grails - lecture 1
groovy & grails - lecture 1
Alexandre Masselot
 
Make Your Ruby Script Confusing
Make Your Ruby Script ConfusingMake Your Ruby Script Confusing
Make Your Ruby Script Confusing
SATOSHI TAGOMORI
 
Scala the-good-parts
Scala the-good-partsScala the-good-parts
Scala the-good-parts
Fuqiang Wang
 
TypeProf for IDE: Enrich Development Experience without Annotations
TypeProf for IDE: Enrich Development Experience without AnnotationsTypeProf for IDE: Enrich Development Experience without Annotations
TypeProf for IDE: Enrich Development Experience without Annotations
mametter
 
Large Scale JavaScript with TypeScript
Large Scale JavaScript with TypeScriptLarge Scale JavaScript with TypeScript
Large Scale JavaScript with TypeScriptOliver Zeigermann
 
Beginning Java for .NET developers
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developers
Andrei Rinea
 
Not Everything is an Object - Rocksolid Tour 2013
Not Everything is an Object  - Rocksolid Tour 2013Not Everything is an Object  - Rocksolid Tour 2013
Not Everything is an Object - Rocksolid Tour 2013Gary Short
 
Kotlin
KotlinKotlin
A Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and UnderstandingA Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and Understanding
mametter
 
Lock-free algorithms for Kotlin Coroutines
Lock-free algorithms for Kotlin CoroutinesLock-free algorithms for Kotlin Coroutines
Lock-free algorithms for Kotlin Coroutines
Roman Elizarov
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
felixbillon
 
Type Profiler: Ambitious Type Inference for Ruby 3
Type Profiler: Ambitious Type Inference for Ruby 3Type Profiler: Ambitious Type Inference for Ruby 3
Type Profiler: Ambitious Type Inference for Ruby 3
mametter
 
Test::Kantan - Perl and Testing
Test::Kantan - Perl and TestingTest::Kantan - Perl and Testing
Test::Kantan - Perl and Testing
Tokuhiro Matsuno
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation Guide
Nascenia IT
 
Java principles
Java principlesJava principles
Java principles
Adel Jaffan
 
Playing with SIMBL - Mobile Jazz Inspirational Talks
Playing with SIMBL - Mobile Jazz Inspirational TalksPlaying with SIMBL - Mobile Jazz Inspirational Talks
Playing with SIMBL - Mobile Jazz Inspirational Talks
Mobile Jazz
 

What's hot (20)

Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
Partial Continuations, Lessons From JavaScript and Guile in 2012 (Quasiconf 2...
 
CocoaConf DC - Automate with Swift - Tony Ingraldi
CocoaConf DC -  Automate with Swift - Tony IngraldiCocoaConf DC -  Automate with Swift - Tony Ingraldi
CocoaConf DC - Automate with Swift - Tony Ingraldi
 
Why Scala?
Why Scala?Why Scala?
Why Scala?
 
A Static Type Analyzer of Untyped Ruby Code for Ruby 3
A Static Type Analyzer of Untyped Ruby Code for Ruby 3A Static Type Analyzer of Untyped Ruby Code for Ruby 3
A Static Type Analyzer of Untyped Ruby Code for Ruby 3
 
groovy & grails - lecture 1
groovy & grails - lecture 1groovy & grails - lecture 1
groovy & grails - lecture 1
 
Make Your Ruby Script Confusing
Make Your Ruby Script ConfusingMake Your Ruby Script Confusing
Make Your Ruby Script Confusing
 
Scala the-good-parts
Scala the-good-partsScala the-good-parts
Scala the-good-parts
 
TypeProf for IDE: Enrich Development Experience without Annotations
TypeProf for IDE: Enrich Development Experience without AnnotationsTypeProf for IDE: Enrich Development Experience without Annotations
TypeProf for IDE: Enrich Development Experience without Annotations
 
Large Scale JavaScript with TypeScript
Large Scale JavaScript with TypeScriptLarge Scale JavaScript with TypeScript
Large Scale JavaScript with TypeScript
 
Beginning Java for .NET developers
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developers
 
Not Everything is an Object - Rocksolid Tour 2013
Not Everything is an Object  - Rocksolid Tour 2013Not Everything is an Object  - Rocksolid Tour 2013
Not Everything is an Object - Rocksolid Tour 2013
 
Kotlin
KotlinKotlin
Kotlin
 
A Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and UnderstandingA Type-level Ruby Interpreter for Testing and Understanding
A Type-level Ruby Interpreter for Testing and Understanding
 
Lock-free algorithms for Kotlin Coroutines
Lock-free algorithms for Kotlin CoroutinesLock-free algorithms for Kotlin Coroutines
Lock-free algorithms for Kotlin Coroutines
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
Type Profiler: Ambitious Type Inference for Ruby 3
Type Profiler: Ambitious Type Inference for Ruby 3Type Profiler: Ambitious Type Inference for Ruby 3
Type Profiler: Ambitious Type Inference for Ruby 3
 
Test::Kantan - Perl and Testing
Test::Kantan - Perl and TestingTest::Kantan - Perl and Testing
Test::Kantan - Perl and Testing
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation Guide
 
Java principles
Java principlesJava principles
Java principles
 
Playing with SIMBL - Mobile Jazz Inspirational Talks
Playing with SIMBL - Mobile Jazz Inspirational TalksPlaying with SIMBL - Mobile Jazz Inspirational Talks
Playing with SIMBL - Mobile Jazz Inspirational Talks
 

Similar to Introduction to Type Level Programming

What's coming to c# (Tel-Aviv, 2018)
What's coming to c# (Tel-Aviv, 2018)What's coming to c# (Tel-Aviv, 2018)
What's coming to c# (Tel-Aviv, 2018)
Moaid Hathot
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
Ruslan Shevchenko
 
Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinay
Viplav Jain
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
Azilen Technologies Pvt. Ltd.
 
XAML/C# to HTML/JS
XAML/C# to HTML/JSXAML/C# to HTML/JS
XAML/C# to HTML/JS
Michael Haberman
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
Shimi Bandiel
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
Abbas Raza
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
Iwan van der Kleijn
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaScala Italy
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
Martin Odersky
 
Return of c++
Return of c++Return of c++
Return of c++
Yongwei Wu
 
Java プログラマーのための Swift 入門 #中央線Meetup
Java プログラマーのための Swift 入門 #中央線MeetupJava プログラマーのための Swift 入門 #中央線Meetup
Java プログラマーのための Swift 入門 #中央線Meetup
Shinya Mochida
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
Mohamed Wael
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!
Alessandro Giorgetti
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless
Jared Roesch
 
Haxe by sergei egorov
Haxe by sergei egorovHaxe by sergei egorov
Haxe by sergei egorov
Sergei Egorov
 
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
AboutYouGmbH
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
Apache Traffic Server
 

Similar to Introduction to Type Level Programming (20)

What's coming to c# (Tel-Aviv, 2018)
What's coming to c# (Tel-Aviv, 2018)What's coming to c# (Tel-Aviv, 2018)
What's coming to c# (Tel-Aviv, 2018)
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
 
Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinay
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
XAML/C# to HTML/JS
XAML/C# to HTML/JSXAML/C# to HTML/JS
XAML/C# to HTML/JS
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of Scala
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
 
Return of c++
Return of c++Return of c++
Return of c++
 
Java プログラマーのための Swift 入門 #中央線Meetup
Java プログラマーのための Swift 入門 #中央線MeetupJava プログラマーのための Swift 入門 #中央線Meetup
Java プログラマーのための Swift 入門 #中央線Meetup
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless
 
Haxe by sergei egorov
Haxe by sergei egorovHaxe by sergei egorov
Haxe by sergei egorov
 
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 

Recently uploaded

Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 

Recently uploaded (20)

Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 

Introduction to Type Level Programming

  • 1. Introduction to Type Level Programming Or: How to blame the Scala compiler when nothing works Yuval Itzchakov 13/02/2018
  • 2. YuvalItzchakov 2 • Developer @ Clicktale for the past 3 years • Previously developer @ IDF (8200) @yuvalitzchakov https://stackoverflow.com/users/1870803/yuval-itzchakov h http://asyncified.io https://fpchat-invite.herokuapp.com/ (yuval.Itzchakov)
  • 3. Agenda 3 • Type Level Programming In a Nutshell • Show[A] • Implicits • Typeclass Pattern • Generic Derivation
  • 4. TypeLevelProgramming 4 • The compiler is the verification tool for our program. • Can we make it do more? • How about generating types at compile time for us?
  • 6. Show[A] 6 trait Show[A] { def show(a: A): String } • Defines a string representation for a type. • Allows us to define custom representations for closed types.
  • 7. PrintingaArray[Byte] 7 We want to print a byte array: val bytes = Array[Byte](30, 57, 92) println(bytes) // [B@6615435c On the other hand, given a Show instance: val showBytes = new Show[Array[Byte]] { override def show(arr: Array[Byte]): String = arr.map("%02X" format _).mkString(",") } println(showBytes.show(bytes)) // 1E,39,5C
  • 8. Wherewe’regoing 8 Given any case class: case class Person(firstName: String, lastName: String, age: Int) We’ll be able to automatically derive a Show instance for it: val p = Person("yuval", "itzchakov", 30) val personShower: Show[Person] = ??? // Magic personShower.show(p) // yuval, itzchakov, 30
  • 9. Startingsimple 9 Let’s see how we define Show instances for primitive types
  • 10. Nice,butalittleugly 10 • Can we do better? • YES! IMPLICITS! implicit val intEncoder: Show[Int] = new Show[Int] { override def show(i: Int): String = i.toString }
  • 11. Implicits 11 • An implicit parameter is used to summon the Show[A] trait. • Scala compiler searches for a suitable implicit in scope. • If found, the compiler fills in the right instance at compile time. • Implicit resolution works recursively.
  • 12. TypeclassPattern 13 • Defining common behavior for types, without inheritance. • Trait definition with a polymorphic type • Concrete implicit instances • Originated in Haskell • A form of ad-hoc polymorphism (A.K.A overloading)
  • 13. TypeclassDefinition 14 Any method requiring the type class, asks for it implicitly from the compiler: def log[A](a: A)(implicit shower: Show[A]): String = { shower.show(a) } println(log(10)) // log(10)(intEncoder) -> 10
  • 14. TypeclassPattern 15 The implicit value must be in scope, otherwise: Error:(45, 19) could not find implicit value for parameter show: Show[Int] println(log(10))
  • 15. TypeclassPattern 16 Who uses the typeclass pattern? • Scala Collections – Ordering[A], CanBuildFrom[A] • Circe – Encoder[A] / Decoder[A] • Avro4S – ToRecord[A] / FromRecord[A] • Cats / Scalaz – Functor[A], Monoid[A], Applicative[A] • Many more!
  • 16. Canwedo better? 17 • Can the compiler resolve, based on existing primitive implicits, more complex types? • How about a Tuple2 of primitives? type Person = (String, (String, Int)) type Person = Tuple2[String, Tuple2[String, Int]]
  • 17. 18
  • 18. RecursiveImplicitResolution 19 type Person = Tuple2[String, Tuple2[String, Int]] implicit def tupleShow[Head, Tail]( implicit headShow: Show[Head], tailShow: Show[Tail]) Show[String] Do I have an implicit for Tuple2? Show[Tuple[String, Int]] Recurse
  • 19. RecursiveImplicitResolution 20 type Person = Tuple2[String, Tuple2[String, Int]] Do I have an implicit for Tuple2? implicit def tupleShow[Head, Tail]( implicit headShow: Show[Head], tailShow: Show[Tail]) Show[String] Show[Int]
  • 20. But… 21 • In real life, we usually don’t encode types as tuples • And we want to abstract over arity (Tuple3, Tuple4, TupleN) • We really want to encode with case classes • Can we do that?
  • 21. Whatarecaseclasses,really? 22 • Named tuples on steroids. • Compiler generated method implementations. • Can be of any arity ( >= Scala 2.11). • How do we deal with that? Can they be represented generically?
  • 22. Yes,wecan! 23 • Using HList (Heterogenous List) • Heterogenous for holding different types val hlist: ::[String, ::[Boolean, ::[Int, HNil]]] = "Scala-IL" :: true :: 42 :: HNil val meetUp: String = hlist.head // “Scala-IL” val isItAwesome: Boolean = hlist.tail.head // true
  • 23. 24
  • 24. shapeless 25 “shapeless is a type class and dependent type based generic programming library for Scala” (from GitHub). • Provides us with a vast amount of building blocks for TLP • Consumed by many popular libraries in the ecosystem: • circe • avro4s • scodec • spray
  • 25. Interesting.. 26 • Can we rework our example to derive a Show[A] instance for any case class using HList? • Let’s try!
  • 26. Evolution 27 type Person = Tuple2[String, Tuple2[String, Int]] case class Person(firstName: String, lastName: String, age: Int) type Person = shapeless.::[String, shapeless.::[String, shapeless.::[Int, HNil]]]
  • 27. 28Confidential • Implicit resolution error messages • Use tek/splain (https://github.com/tek/splain) • Things can become… complex def collect[HL <: HList, RL <: HList, KL <: HList, ZL <: HList] (implicit iso: LabelledGeneric.Aux[C, HL] , annot: Annotations.Aux[A, C, RL] , keys: Keys.Aux[HL, KL] , zip: Zip.Aux[KL :: RL :: HNil, ZL] , leftFolder: LeftFolder.Aux[ZL, B, Collector.type, B]): B Limitations
  • 28. 29Confidential • Compile times – Take care of your implicit scope! Limitations
  • 29. 30Confidential • You’re probably using it already • Building codecs (JSON, Avro, XML, or custom) • Abstracting over arity • Updating nested data structured (lenses) • Type safe casts (when you really must) Where TLP Meets You
  • 30. 31Confidential • The Scala compiler is a powerful tool. • We can leverage it to do amazing things, like generically derive types for us. • shapeless is a powerful building block in that process. • Mixing it all together, type level programming becomes immensely powerful. Conclusion
  • 32. 33Confidential • The Type Astronaut’s Guide to Shapeless (Dave Gurnell) https://github.com/davegurnell/shapeless-guide • Daniel Spiewak – High Wizardy in the Land Of Scala https://vimeo.com/28793245 • Aaron Levin – Mastering Typeclass Induction https://www.youtube.com/watch?v=Nm4OIhjjA2o • Li Haoyi - Implicit Design Patterns in Scala http://www.lihaoyi.com/post/ImplicitDesignPatternsinScala.html Resources
  • 33. Thank you for listening! Questions?