SlideShare a Scribd company logo
1 of 12
Download to read offline
Type-level programming
Dmytro Mitin
https://stepik.org/course/Introduction-to-programming-
with-dependent-types-in-Scala-2294/
March 2017
Dmytro Mitin Type-level programming
Type-level programming
Value level Type level
ADT values: val x object X
Members: def x, val x type X
def f(x) type F[X]
a.b A#B
x : T X <: T
new A(b) A[B]
Dmytro Mitin Type-level programming
Value-level booleans
sealed trait Bool {
def not: Bool
def &&(b: Bool): Bool
def ||(b: Bool): Bool
def ifElse[C](t: => C, f: => C): C
}
case object True extends Bool {
def not: Bool = False
def &&(b: Bool): Bool = b
def ||(b: Bool): Bool = True
def ifElse[C](t: => C, f: => C): C = t
}
case object False extends Bool {
def not: Bool = True
def &&(b: Bool): Bool = False
def ||(b: Bool): Bool = b
def ifElse[C](t: => C, f: => C): C = f
} Dmytro Mitin Type-level programming
Type-level booleans
sealed trait Bool {
type Not <: Bool
type && [B <: Bool] <: Bool
type || [B <: Bool] <: Bool
type IfElse[C, T <: C, F <: C] <: C
}
type True = True.type
type False = False.type
case object True extends Bool {
type Not = False
type && [B <: Bool] = B
type || [B <: Bool] = True
type IfElse[C, T <: C, F <: C] = T
}
Dmytro Mitin Type-level programming
Type-level booleans
case object False extends Bool {
type Not = True
type && [B <: Bool] = False
type || [B <: Bool] = B
type IfElse[C, T <: C, F <: C] = F
}
implicitly[False# Not =:= True]
implicitly[(True# && [False]) =:= False]
implicitly[(True# || [False]) =:= True]
implicitly[False# IfElse[Any, Int, String] =:= String]
// compile time!
Dmytro Mitin Type-level programming
Value-level natural numbers
sealed trait Nat {
def ++ : Nat = Succ(this)
def +(x: Nat): Nat
def *(x: Nat): Nat
}
case object Zero extends Nat {
def +(x: Nat): Nat = x
def *(x: Nat): Nat = Zero
}
case class Succ(n: Nat) extends Nat {
def +(x: Nat): Nat = Succ(n.+(x))
def *(x: Nat): Nat = n.*(x).+(x)
}
Dmytro Mitin Type-level programming
Type-level natural numbers
sealed trait Nat {
type This >: this.type <: Nat
type ++ = Succ[This]
type + [ <: Nat] <: Nat
type * [ <: Nat] <: Nat
}
final object Zero extends Nat {
type This = Zero
type + [X <: Nat] = X
type * [ <: Nat] = Zero
}
type Zero = Zero.type
final class Succ[N <: Nat] extends Nat {
type This = Succ[N]
type + [X <: Nat] = Succ[N# + [X]]
type * [X <: Nat] = (N# * [X])# + [X]
}
Dmytro Mitin Type-level programming
Type-level natural numbers
type 0 = Zero
type 1 = 0 # ++
type 2 = 1 # ++
type 3 = 2 # ++
type 4 = 3 # ++
type 5 = 4 # ++
type 6 = 5 # ++
type 7 = 6 # ++
type 8 = 7 # ++
implicitly[False# IfElse[Nat, 2, 4] =:= 4]
implicitly[ 2# + [ 3] =:= 5]
implicitly[ 2# * [ 3] =:= 6]
Dmytro Mitin Type-level programming
Value-level factorial and Fibonacci numbers
def factorial(n: Nat): Nat = n match {
case Zero => Succ(Zero)
case Succ(m) =>
val x = factorial(m)
x.*(Succ(m))
}
def fibonacci(n: Nat): Nat = n match {
case Zero => Zero
case Succ(Zero) => Succ(Zero)
case Succ(Succ(m)) =>
val x = fibonacci(m)
val y = fibonacci(Succ(m))
x.+(y)
}
Dmytro Mitin Type-level programming
Type-level factorial
sealed trait Factorial[N <: Nat] { type Res <: Nat }
implicit object factorial0 extends Factorial[ 0] { type Res = 1 }
implicit def factorial[N <: Nat, X <: Nat](implicit
fact: Factorial[N] { type Res = X }
) = new Factorial[Succ[N]] { type Res = X# * [Succ[N]] }
implicitly[Factorial[ 0] { type Res = 1 }]
implicitly[Factorial[ 1] { type Res = 1 }]
implicitly[Factorial[ 2] { type Res = 2 }]
implicitly[Factorial[ 3] { type Res = 6 }]
Dmytro Mitin Type-level programming
Type-level Fibonacci numbers
sealed trait Fibonacci[N <: Nat] { type Res <: Nat }
implicit object fibonacci0 extends Fibonacci[ 0] { type Res = 0 }
implicit object fibonacci1 extends Fibonacci[ 1] { type Res = 1 }
implicit def fibonacci[N <: Nat, X <: Nat, Y <: Nat](implicit
fib1: Fibonacci[N] { type Res = X },
fib2: Fibonacci[Succ[N]] { type Res = Y }
) = new Fibonacci[Succ[Succ[N]]] { type Res = X# + [Y] }
implicitly[Fibonacci[ 0] { type Res = 0 }]
implicitly[Fibonacci[ 1] { type Res = 1 }]
implicitly[Fibonacci[ 2] { type Res = 1 }]
implicitly[Fibonacci[ 3] { type Res = 2 }]
implicitly[Fibonacci[ 4] { type Res = 3 }]
implicitly[Fibonacci[ 5] { type Res = 5 }]
implicitly[Fibonacci[ 6] { type Res = 8 }]
Dmytro Mitin Type-level programming
Shapeless
build.sbt
libraryDependencies += "com.chuusai" %% "shapeless" % "2.3.2"
import shapeless.Nat.
val x: 0 = 0
val y: 1 = 1
val z: 2 = 2
val t: 3 = 3
// ...
Dmytro Mitin Type-level programming

More Related Content

What's hot

C++ Returning Objects
C++ Returning ObjectsC++ Returning Objects
C++ Returning ObjectsJay Patel
 
Objective C Primer (with ref to C#)
Objective C  Primer (with ref to C#)Objective C  Primer (with ref to C#)
Objective C Primer (with ref to C#)Hock Leng PUAH
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 
Tutconstructordes
TutconstructordesTutconstructordes
TutconstructordesNiti Arora
 
Concept of constructors
Concept of constructorsConcept of constructors
Concept of constructorskunj desai
 
Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritancezindadili
 
Essence of the iterator pattern
Essence of the iterator patternEssence of the iterator pattern
Essence of the iterator patternMarkus Klink
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and ClassesIntro C# Book
 

What's hot (19)

Templates2
Templates2Templates2
Templates2
 
C++ Template
C++ TemplateC++ Template
C++ Template
 
Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Templates
TemplatesTemplates
Templates
 
C++ Returning Objects
C++ Returning ObjectsC++ Returning Objects
C++ Returning Objects
 
Objective C Primer (with ref to C#)
Objective C  Primer (with ref to C#)Objective C  Primer (with ref to C#)
Objective C Primer (with ref to C#)
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
C++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLESC++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLES
 
Tutconstructordes
TutconstructordesTutconstructordes
Tutconstructordes
 
Concept of constructors
Concept of constructorsConcept of constructors
Concept of constructors
 
Bc0037
Bc0037Bc0037
Bc0037
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Templates
TemplatesTemplates
Templates
 
Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritance
 
Exercise1 java
Exercise1 javaExercise1 java
Exercise1 java
 
Essence of the iterator pattern
Essence of the iterator patternEssence of the iterator pattern
Essence of the iterator pattern
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and Classes
 

Viewers also liked

Scala dreaded underscore
Scala dreaded underscoreScala dreaded underscore
Scala dreaded underscoreRUDDER
 
Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由Yukishige Nakajo
 
Generations Of Programming Languages
Generations Of Programming LanguagesGenerations Of Programming Languages
Generations Of Programming Languagessebrown
 
Programming languages
Programming languagesProgramming languages
Programming languagesAkash Varaiya
 
Eliminators into dependent types
Eliminators into dependent typesEliminators into dependent types
Eliminators into dependent typesDmytro Mitin
 

Viewers also liked (8)

Type classes
Type classesType classes
Type classes
 
Interpolation
InterpolationInterpolation
Interpolation
 
Scala dreaded underscore
Scala dreaded underscoreScala dreaded underscore
Scala dreaded underscore
 
Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由
 
Generations Of Programming Languages
Generations Of Programming LanguagesGenerations Of Programming Languages
Generations Of Programming Languages
 
Programming languages
Programming languagesProgramming languages
Programming languages
 
Computer languages
Computer languagesComputer languages
Computer languages
 
Eliminators into dependent types
Eliminators into dependent typesEliminators into dependent types
Eliminators into dependent types
 

Similar to Type-level programming

13 - Scala. Dependent pair type (Σ-type)
13 - Scala. Dependent pair type (Σ-type)13 - Scala. Dependent pair type (Σ-type)
13 - Scala. Dependent pair type (Σ-type)Roman Brovko
 
04 - Scala. Type of natural numbers
04 - Scala. Type of natural numbers04 - Scala. Type of natural numbers
04 - Scala. Type of natural numbersRoman Brovko
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingTip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingPatrick Viafore
 
Generic Functional Programming with Type Classes
Generic Functional Programming with Type ClassesGeneric Functional Programming with Type Classes
Generic Functional Programming with Type ClassesTapio Rautonen
 
16 - Scala. Type of length-indexed vectors
16 - Scala. Type of length-indexed vectors16 - Scala. Type of length-indexed vectors
16 - Scala. Type of length-indexed vectorsRoman Brovko
 
Peyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slidePeyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slideTakayuki Muranushi
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)Eric Torreborre
 
Python-3-compiled-Cheat-Sheet-version-3.pdf
Python-3-compiled-Cheat-Sheet-version-3.pdfPython-3-compiled-Cheat-Sheet-version-3.pdf
Python-3-compiled-Cheat-Sheet-version-3.pdfletsdism
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator PatternEric Torreborre
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryDatabricks
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryDatabricks
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
Machine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting ConcernsMachine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting Concernssaintiss
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoidsLuka Jacobowitz
 

Similar to Type-level programming (20)

13 - Scala. Dependent pair type (Σ-type)
13 - Scala. Dependent pair type (Σ-type)13 - Scala. Dependent pair type (Σ-type)
13 - Scala. Dependent pair type (Σ-type)
 
04 - Scala. Type of natural numbers
04 - Scala. Type of natural numbers04 - Scala. Type of natural numbers
04 - Scala. Type of natural numbers
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingTip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python Typing
 
Generic Functional Programming with Type Classes
Generic Functional Programming with Type ClassesGeneric Functional Programming with Type Classes
Generic Functional Programming with Type Classes
 
16 - Scala. Type of length-indexed vectors
16 - Scala. Type of length-indexed vectors16 - Scala. Type of length-indexed vectors
16 - Scala. Type of length-indexed vectors
 
Functional DDD
Functional DDDFunctional DDD
Functional DDD
 
Thesis
ThesisThesis
Thesis
 
Peyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slidePeyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slide
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
 
Python-3-compiled-Cheat-Sheet-version-3.pdf
Python-3-compiled-Cheat-Sheet-version-3.pdfPython-3-compiled-Cheat-Sheet-version-3.pdf
Python-3-compiled-Cheat-Sheet-version-3.pdf
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Docimp
DocimpDocimp
Docimp
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love Story
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love Story
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Machine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting ConcernsMachine-level Composition of Modularized Crosscutting Concerns
Machine-level Composition of Modularized Crosscutting Concerns
 
VB net lab.pdf
VB net lab.pdfVB net lab.pdf
VB net lab.pdf
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
 

Recently uploaded

TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...ssifa0344
 
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisRaman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisDiwakar Mishra
 
Zoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfZoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfSumit Kumar yadav
 
Hire 💕 9907093804 Hooghly Call Girls Service Call Girls Agency
Hire 💕 9907093804 Hooghly Call Girls Service Call Girls AgencyHire 💕 9907093804 Hooghly Call Girls Service Call Girls Agency
Hire 💕 9907093804 Hooghly Call Girls Service Call Girls AgencySheetal Arora
 
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 60009654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000Sapana Sha
 
Green chemistry and Sustainable development.pptx
Green chemistry  and Sustainable development.pptxGreen chemistry  and Sustainable development.pptx
Green chemistry and Sustainable development.pptxRajatChauhan518211
 
Orientation, design and principles of polyhouse
Orientation, design and principles of polyhouseOrientation, design and principles of polyhouse
Orientation, design and principles of polyhousejana861314
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxUmerFayaz5
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bSérgio Sacani
 
Biological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfBiological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfmuntazimhurra
 
Broad bean, Lima Bean, Jack bean, Ullucus.pptx
Broad bean, Lima Bean, Jack bean, Ullucus.pptxBroad bean, Lima Bean, Jack bean, Ullucus.pptx
Broad bean, Lima Bean, Jack bean, Ullucus.pptxjana861314
 
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPirithiRaju
 
Botany krishna series 2nd semester Only Mcq type questions
Botany krishna series 2nd semester Only Mcq type questionsBotany krishna series 2nd semester Only Mcq type questions
Botany krishna series 2nd semester Only Mcq type questionsSumit Kumar yadav
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRDelhi Call girls
 
GFP in rDNA Technology (Biotechnology).pptx
GFP in rDNA Technology (Biotechnology).pptxGFP in rDNA Technology (Biotechnology).pptx
GFP in rDNA Technology (Biotechnology).pptxAleenaTreesaSaji
 
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPirithiRaju
 
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Sérgio Sacani
 
VIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PVIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PPRINCE C P
 
Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)PraveenaKalaiselvan1
 

Recently uploaded (20)

TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
TEST BANK For Radiologic Science for Technologists, 12th Edition by Stewart C...
 
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisRaman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
 
Zoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdfZoology 4th semester series (krishna).pdf
Zoology 4th semester series (krishna).pdf
 
Hire 💕 9907093804 Hooghly Call Girls Service Call Girls Agency
Hire 💕 9907093804 Hooghly Call Girls Service Call Girls AgencyHire 💕 9907093804 Hooghly Call Girls Service Call Girls Agency
Hire 💕 9907093804 Hooghly Call Girls Service Call Girls Agency
 
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 60009654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
9654467111 Call Girls In Raj Nagar Delhi Short 1500 Night 6000
 
Green chemistry and Sustainable development.pptx
Green chemistry  and Sustainable development.pptxGreen chemistry  and Sustainable development.pptx
Green chemistry and Sustainable development.pptx
 
Orientation, design and principles of polyhouse
Orientation, design and principles of polyhouseOrientation, design and principles of polyhouse
Orientation, design and principles of polyhouse
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptx
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
 
Biological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfBiological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdf
 
Broad bean, Lima Bean, Jack bean, Ullucus.pptx
Broad bean, Lima Bean, Jack bean, Ullucus.pptxBroad bean, Lima Bean, Jack bean, Ullucus.pptx
Broad bean, Lima Bean, Jack bean, Ullucus.pptx
 
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
 
Botany krishna series 2nd semester Only Mcq type questions
Botany krishna series 2nd semester Only Mcq type questionsBotany krishna series 2nd semester Only Mcq type questions
Botany krishna series 2nd semester Only Mcq type questions
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
 
GFP in rDNA Technology (Biotechnology).pptx
GFP in rDNA Technology (Biotechnology).pptxGFP in rDNA Technology (Biotechnology).pptx
GFP in rDNA Technology (Biotechnology).pptx
 
The Philosophy of Science
The Philosophy of ScienceThe Philosophy of Science
The Philosophy of Science
 
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
 
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
 
VIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PVIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C P
 
Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)
 

Type-level programming

  • 2. Type-level programming Value level Type level ADT values: val x object X Members: def x, val x type X def f(x) type F[X] a.b A#B x : T X <: T new A(b) A[B] Dmytro Mitin Type-level programming
  • 3. Value-level booleans sealed trait Bool { def not: Bool def &&(b: Bool): Bool def ||(b: Bool): Bool def ifElse[C](t: => C, f: => C): C } case object True extends Bool { def not: Bool = False def &&(b: Bool): Bool = b def ||(b: Bool): Bool = True def ifElse[C](t: => C, f: => C): C = t } case object False extends Bool { def not: Bool = True def &&(b: Bool): Bool = False def ||(b: Bool): Bool = b def ifElse[C](t: => C, f: => C): C = f } Dmytro Mitin Type-level programming
  • 4. Type-level booleans sealed trait Bool { type Not <: Bool type && [B <: Bool] <: Bool type || [B <: Bool] <: Bool type IfElse[C, T <: C, F <: C] <: C } type True = True.type type False = False.type case object True extends Bool { type Not = False type && [B <: Bool] = B type || [B <: Bool] = True type IfElse[C, T <: C, F <: C] = T } Dmytro Mitin Type-level programming
  • 5. Type-level booleans case object False extends Bool { type Not = True type && [B <: Bool] = False type || [B <: Bool] = B type IfElse[C, T <: C, F <: C] = F } implicitly[False# Not =:= True] implicitly[(True# && [False]) =:= False] implicitly[(True# || [False]) =:= True] implicitly[False# IfElse[Any, Int, String] =:= String] // compile time! Dmytro Mitin Type-level programming
  • 6. Value-level natural numbers sealed trait Nat { def ++ : Nat = Succ(this) def +(x: Nat): Nat def *(x: Nat): Nat } case object Zero extends Nat { def +(x: Nat): Nat = x def *(x: Nat): Nat = Zero } case class Succ(n: Nat) extends Nat { def +(x: Nat): Nat = Succ(n.+(x)) def *(x: Nat): Nat = n.*(x).+(x) } Dmytro Mitin Type-level programming
  • 7. Type-level natural numbers sealed trait Nat { type This >: this.type <: Nat type ++ = Succ[This] type + [ <: Nat] <: Nat type * [ <: Nat] <: Nat } final object Zero extends Nat { type This = Zero type + [X <: Nat] = X type * [ <: Nat] = Zero } type Zero = Zero.type final class Succ[N <: Nat] extends Nat { type This = Succ[N] type + [X <: Nat] = Succ[N# + [X]] type * [X <: Nat] = (N# * [X])# + [X] } Dmytro Mitin Type-level programming
  • 8. Type-level natural numbers type 0 = Zero type 1 = 0 # ++ type 2 = 1 # ++ type 3 = 2 # ++ type 4 = 3 # ++ type 5 = 4 # ++ type 6 = 5 # ++ type 7 = 6 # ++ type 8 = 7 # ++ implicitly[False# IfElse[Nat, 2, 4] =:= 4] implicitly[ 2# + [ 3] =:= 5] implicitly[ 2# * [ 3] =:= 6] Dmytro Mitin Type-level programming
  • 9. Value-level factorial and Fibonacci numbers def factorial(n: Nat): Nat = n match { case Zero => Succ(Zero) case Succ(m) => val x = factorial(m) x.*(Succ(m)) } def fibonacci(n: Nat): Nat = n match { case Zero => Zero case Succ(Zero) => Succ(Zero) case Succ(Succ(m)) => val x = fibonacci(m) val y = fibonacci(Succ(m)) x.+(y) } Dmytro Mitin Type-level programming
  • 10. Type-level factorial sealed trait Factorial[N <: Nat] { type Res <: Nat } implicit object factorial0 extends Factorial[ 0] { type Res = 1 } implicit def factorial[N <: Nat, X <: Nat](implicit fact: Factorial[N] { type Res = X } ) = new Factorial[Succ[N]] { type Res = X# * [Succ[N]] } implicitly[Factorial[ 0] { type Res = 1 }] implicitly[Factorial[ 1] { type Res = 1 }] implicitly[Factorial[ 2] { type Res = 2 }] implicitly[Factorial[ 3] { type Res = 6 }] Dmytro Mitin Type-level programming
  • 11. Type-level Fibonacci numbers sealed trait Fibonacci[N <: Nat] { type Res <: Nat } implicit object fibonacci0 extends Fibonacci[ 0] { type Res = 0 } implicit object fibonacci1 extends Fibonacci[ 1] { type Res = 1 } implicit def fibonacci[N <: Nat, X <: Nat, Y <: Nat](implicit fib1: Fibonacci[N] { type Res = X }, fib2: Fibonacci[Succ[N]] { type Res = Y } ) = new Fibonacci[Succ[Succ[N]]] { type Res = X# + [Y] } implicitly[Fibonacci[ 0] { type Res = 0 }] implicitly[Fibonacci[ 1] { type Res = 1 }] implicitly[Fibonacci[ 2] { type Res = 1 }] implicitly[Fibonacci[ 3] { type Res = 2 }] implicitly[Fibonacci[ 4] { type Res = 3 }] implicitly[Fibonacci[ 5] { type Res = 5 }] implicitly[Fibonacci[ 6] { type Res = 8 }] Dmytro Mitin Type-level programming
  • 12. Shapeless build.sbt libraryDependencies += "com.chuusai" %% "shapeless" % "2.3.2" import shapeless.Nat. val x: 0 = 0 val y: 1 = 1 val z: 2 = 2 val t: 3 = 3 // ... Dmytro Mitin Type-level programming