SlideShare a Scribd company logo
Exploring
Type-Level Programming
in Scala
JORGE VÁSQUEZ
SCALA DEVELOPER
Agenda
● Motivations around Type-Level Programming in Scala
● Background
○ Dependent types
○ Path-dependent types
○ Abstract type members
● Examples of libraries that use Type-Level
Programming
Motivations
around
Type-Level
Programming
Why Type-Level Programming?
● We turn to Scala for type-safety
● But… Sometimes it’s not enough!
Concrete example: Spark DataFrame API
We have lots of potential for runtime bugs!
Concrete example: Spark DataFrame API
df.select(
$"username",
$"tweet"
)
Concrete example: Spark DataFrame API
Error: org.apache.spark.sql.
AnalysisException: cannot
resolve '`username`'
Concrete example: Spark DataFrame API
df.select(
$"timestamp" * 10
)
Concrete example: Spark DataFrame API
Error:
org.apache.spark.sql.
AnalysisException: cannot
resolve '(`timestamp` *
10)' due to data type
mismatch
Concrete example: Spark DataFrame API
df.filter(
$"text" === true
)
// Does not fail
Concrete example: Spark DataFrame API
df.select(
$"text" / 1000
)
// Does not fail
Can we do better?
Scala has a VERY powerful type system,
why not use it?
Concrete example: Spark with Frameless
Frameless helps us to eliminate a lot of bugs…
At compile time!
Concrete example: Spark with Frameless
tds.select(
tds('username),
tds('tweet)
)
Concrete example: Spark with Frameless
// Error:
No column Symbol with
shapeless.tag.Tagged[Str
ing("username")]
Concrete example: Spark with Frameless
tds.select(
tds('timestamp) * 10
)
Concrete example: Spark with Frameless
// Error:
overloaded method value
* with alternatives
[...] cannot be applied
to (Int)
Concrete example: Spark with Frameless
tds.filter(
tds('text) === true
)
Concrete example: Spark with Frameless
// Error:
overloaded method value
=== with alternatives
[...] cannot be applied
to (Boolean)
Concrete example: Spark with Frameless
tds.select(
tds('text) / 1000
)
Concrete example: Spark with Frameless
// Error:
overloaded method value /
with alternatives [...]
cannot be applied to
(Int)
In conclusion...
Type-level Programming lets you eliminate
bugs at compile-time
In conclusion...
Our focus today: Dependent types
Dependent types are the heart of
Type-Level Programming in Scala
What are
Dependent Types?
What are Dependent Types?
● Dependent Types are types that depend on
values.
● With this, we remove the usual separation
between the type and value worlds.
What are Dependent Types?
● Scala is not a fully dependently typed
language.
● However, it supports some form of
Dependent Types, which is called Path
Dependent Types.
How we define Path Dependent Types?
● In Scala, we can define nested components
● For example, a class inside a trait, a
trait inside a class, etc.
How we define Path Dependent Types?
sealed trait Foo {
sealed trait Bar
}
val foo1 = new Foo {}
val foo2 = new Foo {}
val a: Foo#Bar = new foo1.Bar {} // OK
val b: Foo#Bar = new foo2.Bar {} // OK
val c: foo1.Bar = new foo1.Bar {} // OK
val d: foo2.Bar = new foo1.Bar {}
// Required: foo2.Bar, Found: foo1.Bar
How we define Path Dependent Types?
● Another useful tool is Abstract Type
Members, which are types we don’t know
yet and that we can define later
trait Bar {
type T
}
Example 1: Merging Files
Define a merge function, which should take:
● A list of files
● A merge strategy: Single/Multiple/None
● A callback function: Which should expect:
○ A single file if merge strategy is Single
○ A list of files if merge strategy is Multiple
○ A unit value if merge strategy is None
Example 1: Merging Files
import java.io.File
sealed trait MergeStrategy {
type Output
}
object MergeStrategy {
case object Single extends MergeStrategy { type Output = File }
case object Multiple extends MergeStrategy { type Output = List[File] }
case object None extends MergeStrategy { type Output = Unit }
}
def mergeFiles(files: List[File]): File = ???
Example 1: Merging Files
def merge[T](files: List[File], mergeStrategy: MergeStrategy)
(f: mergeStrategy.Output => T): T =
mergeStrategy match {
case MergeStrategy.Single => f(mergeFiles(files))
case MergeStrategy.Multiple => f(files)
case MergeStrategy.None => f(())
}
Example 1: Merging Files
Example 1: Merging Files
def merge[O, T](
files: List[File],
mergeStrategy: MergeStrategy { type Output = O }
)(f: O => T): T =
mergeStrategy match {
case MergeStrategy.Single => f(mergeFiles(files))
case MergeStrategy.Multiple => f(files)
case MergeStrategy.None => f(())
}
Example 1: Merging Files
val files: List[File] = ???
merge(files, MergeStrategy.Single) { file: File =>
// Do some processing
}
merge(files, MergeStrategy.Multiple) { files: List[File] =>
// Do some processing
}
merge(files, MergeStrategy.None) { _: Unit =>
// Do some processing
}
Example 2: Merging Elements
Define a merge function, which should take:
● A list of elements of any type
● A merge strategy: Single/Multiple/None
● A callback function: Which should expect:
○ A single element if merge strategy is Single
○ A list of elements if merge strategy is Multiple
○ A unit value if merge strategy is None
Example 2: Merging Elements
sealed trait MergeStrategy {
type Output[_]
}
object MergeStrategy {
case object Single extends MergeStrategy { type Output[A] = A }
case object Multiple extends MergeStrategy { type Output[A] = List[A] }
case object None extends MergeStrategy { type Output[_] = Unit }
}
def mergeElements[E](elements: List[E]): E = ???
Example 2: Merging Elements
def merge[E, O[_], T](
elements: List[E],
mergeStrategy: MergeStrategy { type Output[A] = O[A] }
)(f: O[E] => T): T =
mergeStrategy match {
case MergeStrategy.Single => f(mergeElements(elements))
case MergeStrategy.Multiple => f(elements)
case MergeStrategy.None => f(())
}
Example 2: Merging Elements
val messages: List[String] = ???
merge(messages, MergeStrategy.Single) { message: String =>
// Do some processing
}
merge(messages, MergeStrategy.Multiple) { messages: List[String] =>
// Do some processing
}
merge(messages, MergeStrategy.None) { _: Unit =>
// Do some processing
}
In conclusion...
● Path-dependent types are the heart and
soul of Scala's type system
● They help you to improve compile-time type
safety
In conclusion...
DOTTY = DOT Calculus = Path Dependent Types
Some example
libraries
Examples of libraries that use
Type Level Programming
● Shapeless: Generic programming
○ Generic Product Type: HList
○ Generic Sum Type: Coproduct
Examples of libraries that use
Type Level Programming
● Frameless: Expressive types for Spark
Examples of libraries that use
Type Level Programming
● Refined: Refinement types
Examples of libraries that use
Type Level Programming
● ZIO SQL: Type-safe SQL queries
References
● Dependent types in Scala, blog post by Yao Li
● Type Level Programming in Scala step by
step, blog series by Luigi Antonini
● The Type Astronaut’s Guide to Shapeless
Book, by Dave Gurnell
● Introduction to Apache Spark with Frameless,
by Brian Clapper
Special thanks
● To micro sphere.it organizers for hosting this
presentation
● To John De Goes for guidance and support
Thank You!
@jorvasquez2301
jorge.vasquez@scalac.io
jorge-vasquez-2301
Contact me

More Related Content

What's hot

Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
jQuery
jQueryjQuery
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rules
Debasish Ghosh
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
John De Goes
 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
Vladimir Parfinenko
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
Sasidhar Kothuru
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
Vladimir Parfinenko
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180
Mahmoud Samir Fayed
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmers
tymon Tobolski
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 
Scala collections
Scala collectionsScala collections
Scala collections
Inphina Technologies
 
Practical cats
Practical catsPractical cats
Practical cats
Raymond Tay
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
Vincent Pradeilles
 
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
scalaconfjp
 
2.1 Recap From Day One
2.1 Recap From Day One2.1 Recap From Day One
2.1 Recap From Day One
retronym
 

What's hot (20)

Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
jQuery
jQueryjQuery
jQuery
 
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rules
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmers
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Scala collections
Scala collectionsScala collections
Scala collections
 
Practical cats
Practical catsPractical cats
Practical cats
 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
 
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
 
2.1 Recap From Day One
2.1 Recap From Day One2.1 Recap From Day One
2.1 Recap From Day One
 

Similar to Exploring type level programming in Scala

Writing DSL with Applicative Functors
Writing DSL with Applicative FunctorsWriting DSL with Applicative Functors
Writing DSL with Applicative Functors
David Galichet
 
Bestiary of Functional Programming with Cats
Bestiary of Functional Programming with CatsBestiary of Functional Programming with Cats
Bestiary of Functional Programming with Cats
💡 Tomasz Kogut
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
Hang Zhao
 
Erlang session1
Erlang session1Erlang session1
Erlang session1
mohamedsamyali
 
Scala google
Scala google Scala google
Scala google
Navneet Kumar
 
Introduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesIntroduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologies
TabassumMaktum
 
The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...
PVS-Studio
 
OOP
OOPOOP
Xml and Co.
Xml and Co.Xml and Co.
Xml and Co.
Findik Dervis
 
InstructionYou’ll probably want to import FileReader, PrintWriter,.pdf
InstructionYou’ll probably want to import FileReader, PrintWriter,.pdfInstructionYou’ll probably want to import FileReader, PrintWriter,.pdf
InstructionYou’ll probably want to import FileReader, PrintWriter,.pdf
arsmobiles
 
pyton Notes6
 pyton Notes6 pyton Notes6
pyton Notes6
Amba Research
 
Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)
Alexander Podkhalyuzin
 
Implicits Inspected and Explained
Implicits Inspected and ExplainedImplicits Inspected and Explained
Implicits Inspected and Explained
Tim Soethout
 
Typeclasses
TypeclassesTypeclasses
Typeclasses
ekalyoncu
 
Google06
Google06Google06
Google06
Zhiwen Guo
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture Three
Angelo Corsaro
 
Java basics
Java basicsJava basics
Java basics
Jitender Jain
 

Similar to Exploring type level programming in Scala (20)

Writing DSL with Applicative Functors
Writing DSL with Applicative FunctorsWriting DSL with Applicative Functors
Writing DSL with Applicative Functors
 
Bestiary of Functional Programming with Cats
Bestiary of Functional Programming with CatsBestiary of Functional Programming with Cats
Bestiary of Functional Programming with Cats
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
 
Erlang session1
Erlang session1Erlang session1
Erlang session1
 
Scala google
Scala google Scala google
Scala google
 
Introduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesIntroduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologies
 
The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...
 
OOP
OOPOOP
OOP
 
Xml and Co.
Xml and Co.Xml and Co.
Xml and Co.
 
InstructionYou’ll probably want to import FileReader, PrintWriter,.pdf
InstructionYou’ll probably want to import FileReader, PrintWriter,.pdfInstructionYou’ll probably want to import FileReader, PrintWriter,.pdf
InstructionYou’ll probably want to import FileReader, PrintWriter,.pdf
 
pyton Notes6
 pyton Notes6 pyton Notes6
pyton Notes6
 
Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)
 
Implicits Inspected and Explained
Implicits Inspected and ExplainedImplicits Inspected and Explained
Implicits Inspected and Explained
 
Typeclasses
TypeclassesTypeclasses
Typeclasses
 
Google06
Google06Google06
Google06
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture Three
 
Java basics
Java basicsJava basics
Java basics
 

More from Jorge Vásquez

Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!
Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!
Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!
Jorge Vásquez
 
Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0
Jorge Vásquez
 
Consiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIO
Consiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIOConsiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIO
Consiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIO
Jorge Vásquez
 
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Jorge Vásquez
 
The Terror-Free Guide to Introducing Functional Scala at Work
The Terror-Free Guide to Introducing Functional Scala at WorkThe Terror-Free Guide to Introducing Functional Scala at Work
The Terror-Free Guide to Introducing Functional Scala at Work
Jorge Vásquez
 
Introduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsIntroduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effects
Jorge Vásquez
 

More from Jorge Vásquez (6)

Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!
Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!
Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!
 
Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0
 
Consiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIO
Consiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIOConsiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIO
Consiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIO
 
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorld
 
The Terror-Free Guide to Introducing Functional Scala at Work
The Terror-Free Guide to Introducing Functional Scala at WorkThe Terror-Free Guide to Introducing Functional Scala at Work
The Terror-Free Guide to Introducing Functional Scala at Work
 
Introduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsIntroduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effects
 

Recently uploaded

Top 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptxTop 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptx
devvsandy
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
Rakesh Kumar R
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
GohKiangHock
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
ssuserad3af4
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 

Recently uploaded (20)

Top 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptxTop 9 Trends in Cybersecurity for 2024.pptx
Top 9 Trends in Cybersecurity for 2024.pptx
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
316895207-SAP-Oil-and-Gas-Downstream-Training.pptx
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 

Exploring type level programming in Scala

  • 3.
  • 4. Agenda ● Motivations around Type-Level Programming in Scala ● Background ○ Dependent types ○ Path-dependent types ○ Abstract type members ● Examples of libraries that use Type-Level Programming
  • 6. Why Type-Level Programming? ● We turn to Scala for type-safety ● But… Sometimes it’s not enough!
  • 7. Concrete example: Spark DataFrame API We have lots of potential for runtime bugs!
  • 8. Concrete example: Spark DataFrame API df.select( $"username", $"tweet" )
  • 9. Concrete example: Spark DataFrame API Error: org.apache.spark.sql. AnalysisException: cannot resolve '`username`'
  • 10. Concrete example: Spark DataFrame API df.select( $"timestamp" * 10 )
  • 11. Concrete example: Spark DataFrame API Error: org.apache.spark.sql. AnalysisException: cannot resolve '(`timestamp` * 10)' due to data type mismatch
  • 12. Concrete example: Spark DataFrame API df.filter( $"text" === true ) // Does not fail
  • 13. Concrete example: Spark DataFrame API df.select( $"text" / 1000 ) // Does not fail
  • 14.
  • 15. Can we do better? Scala has a VERY powerful type system, why not use it?
  • 16. Concrete example: Spark with Frameless Frameless helps us to eliminate a lot of bugs… At compile time!
  • 17. Concrete example: Spark with Frameless tds.select( tds('username), tds('tweet) )
  • 18. Concrete example: Spark with Frameless // Error: No column Symbol with shapeless.tag.Tagged[Str ing("username")]
  • 19. Concrete example: Spark with Frameless tds.select( tds('timestamp) * 10 )
  • 20. Concrete example: Spark with Frameless // Error: overloaded method value * with alternatives [...] cannot be applied to (Int)
  • 21. Concrete example: Spark with Frameless tds.filter( tds('text) === true )
  • 22. Concrete example: Spark with Frameless // Error: overloaded method value === with alternatives [...] cannot be applied to (Boolean)
  • 23. Concrete example: Spark with Frameless tds.select( tds('text) / 1000 )
  • 24. Concrete example: Spark with Frameless // Error: overloaded method value / with alternatives [...] cannot be applied to (Int)
  • 25. In conclusion... Type-level Programming lets you eliminate bugs at compile-time
  • 27. Our focus today: Dependent types Dependent types are the heart of Type-Level Programming in Scala
  • 29. What are Dependent Types? ● Dependent Types are types that depend on values. ● With this, we remove the usual separation between the type and value worlds.
  • 30. What are Dependent Types? ● Scala is not a fully dependently typed language. ● However, it supports some form of Dependent Types, which is called Path Dependent Types.
  • 31. How we define Path Dependent Types? ● In Scala, we can define nested components ● For example, a class inside a trait, a trait inside a class, etc.
  • 32. How we define Path Dependent Types? sealed trait Foo { sealed trait Bar } val foo1 = new Foo {} val foo2 = new Foo {} val a: Foo#Bar = new foo1.Bar {} // OK val b: Foo#Bar = new foo2.Bar {} // OK val c: foo1.Bar = new foo1.Bar {} // OK val d: foo2.Bar = new foo1.Bar {} // Required: foo2.Bar, Found: foo1.Bar
  • 33. How we define Path Dependent Types? ● Another useful tool is Abstract Type Members, which are types we don’t know yet and that we can define later trait Bar { type T }
  • 34. Example 1: Merging Files Define a merge function, which should take: ● A list of files ● A merge strategy: Single/Multiple/None ● A callback function: Which should expect: ○ A single file if merge strategy is Single ○ A list of files if merge strategy is Multiple ○ A unit value if merge strategy is None
  • 35. Example 1: Merging Files import java.io.File sealed trait MergeStrategy { type Output } object MergeStrategy { case object Single extends MergeStrategy { type Output = File } case object Multiple extends MergeStrategy { type Output = List[File] } case object None extends MergeStrategy { type Output = Unit } } def mergeFiles(files: List[File]): File = ???
  • 36. Example 1: Merging Files def merge[T](files: List[File], mergeStrategy: MergeStrategy) (f: mergeStrategy.Output => T): T = mergeStrategy match { case MergeStrategy.Single => f(mergeFiles(files)) case MergeStrategy.Multiple => f(files) case MergeStrategy.None => f(()) }
  • 38. Example 1: Merging Files def merge[O, T]( files: List[File], mergeStrategy: MergeStrategy { type Output = O } )(f: O => T): T = mergeStrategy match { case MergeStrategy.Single => f(mergeFiles(files)) case MergeStrategy.Multiple => f(files) case MergeStrategy.None => f(()) }
  • 39. Example 1: Merging Files val files: List[File] = ??? merge(files, MergeStrategy.Single) { file: File => // Do some processing } merge(files, MergeStrategy.Multiple) { files: List[File] => // Do some processing } merge(files, MergeStrategy.None) { _: Unit => // Do some processing }
  • 40. Example 2: Merging Elements Define a merge function, which should take: ● A list of elements of any type ● A merge strategy: Single/Multiple/None ● A callback function: Which should expect: ○ A single element if merge strategy is Single ○ A list of elements if merge strategy is Multiple ○ A unit value if merge strategy is None
  • 41. Example 2: Merging Elements sealed trait MergeStrategy { type Output[_] } object MergeStrategy { case object Single extends MergeStrategy { type Output[A] = A } case object Multiple extends MergeStrategy { type Output[A] = List[A] } case object None extends MergeStrategy { type Output[_] = Unit } } def mergeElements[E](elements: List[E]): E = ???
  • 42. Example 2: Merging Elements def merge[E, O[_], T]( elements: List[E], mergeStrategy: MergeStrategy { type Output[A] = O[A] } )(f: O[E] => T): T = mergeStrategy match { case MergeStrategy.Single => f(mergeElements(elements)) case MergeStrategy.Multiple => f(elements) case MergeStrategy.None => f(()) }
  • 43. Example 2: Merging Elements val messages: List[String] = ??? merge(messages, MergeStrategy.Single) { message: String => // Do some processing } merge(messages, MergeStrategy.Multiple) { messages: List[String] => // Do some processing } merge(messages, MergeStrategy.None) { _: Unit => // Do some processing }
  • 44. In conclusion... ● Path-dependent types are the heart and soul of Scala's type system ● They help you to improve compile-time type safety
  • 45. In conclusion... DOTTY = DOT Calculus = Path Dependent Types
  • 47. Examples of libraries that use Type Level Programming ● Shapeless: Generic programming ○ Generic Product Type: HList ○ Generic Sum Type: Coproduct
  • 48. Examples of libraries that use Type Level Programming ● Frameless: Expressive types for Spark
  • 49. Examples of libraries that use Type Level Programming ● Refined: Refinement types
  • 50. Examples of libraries that use Type Level Programming ● ZIO SQL: Type-safe SQL queries
  • 51. References ● Dependent types in Scala, blog post by Yao Li ● Type Level Programming in Scala step by step, blog series by Luigi Antonini ● The Type Astronaut’s Guide to Shapeless Book, by Dave Gurnell ● Introduction to Apache Spark with Frameless, by Brian Clapper
  • 52. Special thanks ● To micro sphere.it organizers for hosting this presentation ● To John De Goes for guidance and support