SlideShare una empresa de Scribd logo
1 de 47
A well-typed program never goes wrong julien@kaching.com Silicon Valley Code Camp 2010
µ-Java Imagine Java deprived of  all native types and  all control-flow constructs
Encoding ℕ in µ-Java A number is either zero or the successor of another number
Encoding ℕ in µ-Java interface Number { } class Zero implements Number { } class Successor implements Number { privatefinal Number predecessor;    Successor(Number predecessor) { this.predecessor = predecessor;     } }
Encoding ℕ in µ-Java Number zero = new Zero(); Number one = new Successor(zero); Number two = new Successor(one);
Encoding ℕ in µ-Java Number zero = new Zero(); Number one = new Successor(zero); Number two = new Successor(one); Number three = one.plus(two);
Encoding ℕ in µ-Java interface Number {     Number plus(Number that); }
Encoding ℕ in µ-Java class Zero implements Number {  public Number plus(Number that) {    } }
Encoding ℕ in µ-Java class Zero implements Number {  public Number plus(Number that) { return that;    } }
Encoding ℕ in µ-Java classSuccessor implementsNumber {  privatefinal Number predecessor;     Successor(Number predecessor) { this.predecessor = predecessor; } public Number plus(Number that) {    } }
Encoding ℕ in µ-Java classSuccessor implementsNumber {  privatefinal Number predecessor;     Successor(Number predecessor) { this.predecessor = predecessor; } public Number plus(Number that) { returnnew Successor(predecessor.plus(that));    } }
Encoding ℕ in µ-Java Base case:     0 + n = n Recurrence:     m + n = ((m - 1) + n) + 1
Growing a Language µ-Java expressiveness
Today’s Agenda Practical discussion of Type Safety. Grow your language to make it safer.
“I’ve written well-typed programs before,    and they went wrong!”
This will definitely go wrong scala> defdivide(a: Int, b: Int) = a / b divide: (a: Int,b: Int)Int
This will definitely go wrong scala> defdivide(a: Int, b: Int) = a / b divide: (a: Int,b: Int)Int scala> divide(4, 0) java.lang.ArithmeticException: / by zero at .divide(<console>:5)
Was it well-typed?
Was it well-typed? Yes, but the types didn’t fully convey the complexity of the domain. The type checker doesn’t know you can’t divide by 0 unless it is expressed by the types. How can you grow the language to address this issue?
Division by zero, revisited scala> abstractclass Number(n: Int) scala> caseclass Zero extends Number(0) scala> caseclassNonZero(n: Int) extends Number(n) scala> def number(n: Int) = if (n == 0) Zero elseNonZero(n)
Division by zero, revisited scala> abstractclass Number(n: Int) { def divide(that: NonZero) = number(n / that.n) } scala> number(4).divide(Zero)
Division by zero, revisited scala> abstractclass Number(n: Int) { def divide(that: NonZero) = number(n / that.n) } scala> number(4).divide(Zero) error: type mismatch;  found     : Zero  required: NonZero
Type Safety The extent to which a programming language discourages or prevents type errors. A type error is erroneous program behavior caused by a discrepancy between differing data types.
Well-typed programs never go wrong Preservation  Well typednessof programs remains invariant under the transition rules of the language.  Progress  A well typed program never gets into a state where no further transitions are possible.
Value Types Represents possibly infinite set of similarly kinded data transcending an application's life. Life cycles are meaningless. Value types are immutable. Usually restrict the universe of their underlying types.
Value Types classEmailAddressextends Value<String> { … classPrice extends Value<Long> { … class Id<E extends Entity> extends Value<Long> { …
The 1:1 Principle booleanplaceLimitOrder(Action, Integer, String, Long); booleanplaceLimitOrder(Action, Quantity, Ticker, Price);
Type Safe Bit Field Apple's ticker AAPL. What about Berkshire Hathaway’s?  Google says BRKA, Yahoo! BRK-A, Bloomberg BRK/A and  Reuters BRKa.
Type Safe Bit Field interfaceSecurityTag {   interfaceGoogle extendsSecurityTag{}   interfaceYahoo extendsSecurityTag{}   interfaceBloomberg extendsSecurityTag{}   interfaceReuters extendsSecurityTag{} }
Type Safe Bit Field classTaggedTicker<T extendsSecurityTag>  extends Value<String> { ...
Type Safe Bit Field Price getPriceFromGoogle( TaggedTicker<Google> ticker) { ...   voidsendBuyOrderToBloomberg( TaggedTicker<Bloomberg> ticker, Quantity quantity) { ..
Type Safe Bit Field interface Security {     <T extendsSecurityTag> TaggedTicker<T> getTaggedTicker(Class<T> kind); }
Type Safe Bit Field Map<Class<? extendsSecurityTag>, Long> TAG2MASK =   ImmutableMap.        <Class<? extendsSecurityTag>, Long> builder()             .put(SecurityTag.Google.class, 0x01)             .put(SecurityTag.Yahoo.class, 0x02)             .put(SecurityTag.Bloomberg.class, 0x04)             .put(SecurityTag.Reuters.class, 0x08)             .build();
Type Safe Bit Field <T extendsSecurityTag> void set(Class<T> kind) {   tags = (tags | TAG2MASK.get(kind)); } <T extendsSecurityTag> void unset(Class<T> kind) {   tags = (tags & ~TAG2MASK.get(kind)); }
Invariant Map A bunch of methods in java.util.Map are contravariant on the key type. This makes refactorings extremely error prone. java.util.Map#get(Object) java.util.Map#remove(Object) java.util.Map#containsKey (Object)
Invariant Map voiddoSomething(Map<Ticker, Quote> cache) {    … cache.remove(ticker);
Invariant Map voiddoSomething(Map<Isin, Quote> cache) {       … cache.remove(ticker);
Invariant Map interfaceInvariantMap<K, V> {    V get(K key);   V remove(K key);   ...
Invariant Map classInvariantMaps{ static<K, V> InvariantMap<K, V> newHashMap() { returndelegate(newHashMap<K, V>());   } static<K extends Comparable<? super K>, V>  InvariantMap<K, V> newTreeMap() { returndelegate(newTreeMap<K, V>());   }     …
Option abstractclass Option[T] caseclass None extends Option[Nothing] caseclass Some(x: T) extends Option[T] getUser(id) match { case Some(user) ⇒ … case None ⇒ … }
Option Much more verbose in Java... getUser(id).visit(newOptionVisitor<Unit>() { public Unit caseSome(User user) {         … publicUnit caseNone() {         … })
Option … but still useful! interfaceUserRepository {     Option<User> getUser(Id<User> id); User getUserOrThrow(Id<User> id); }
Abstracting the Control Flow We saw how to grow a language by introducing more types. We can also improve control flow structuresby abstracting the control flow.
Abstracting the Control Flow BigDecimal total = ZERO; for (BigDecimal value : values) { if (value.compareTo(ZERO) > 0) { total.add(value);    } } return total;
Abstracting the Control Flow returnsum(filter(        values,  new Predicate<BigDecimal>() { publicboolean apply(BigDecimal t) { return t.compareTo(ZERO) > 0;              }         }));
Abstracting the Control Flow Easier to re-use operations. The “wiring” between operations is checked by the type system.
References Foundations for Programming Languages John C. Mitchell I Can Has Invariant Mapz? http://eng.kaching.com/2010/07/i-can-has-invariant-mapz.html Type Safe Bit Fields Using Higher-KindedPolymorphism        http://eng.kaching.com/2010/08/type-safe-bit-fields-using-higher.html

Más contenido relacionado

La actualidad más candente

Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpsinghadarsh
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Courseparveen837153
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in JavaGurpreet singh
 
Chapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class InheritanceChapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class InheritanceIt Academy
 
Chapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic ConceptsChapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic ConceptsIt Academy
 
Being Expressive in Code
Being Expressive in CodeBeing Expressive in Code
Being Expressive in CodeEamonn Boyle
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java Ahmad Idrees
 
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJSeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJTed Leung
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedPascal-Louis Perez
 
Dynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner TypingDynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner TypingYusuke Miyazaki
 
Lecture 5 Inheritance
Lecture 5 InheritanceLecture 5 Inheritance
Lecture 5 Inheritancebunnykhan
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharphmanjarawala
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpRaga Vahini
 

La actualidad más candente (17)

Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Chapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class InheritanceChapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class Inheritance
 
Ch6
Ch6Ch6
Ch6
 
Chapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic ConceptsChapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic Concepts
 
Being Expressive in Code
Being Expressive in CodeBeing Expressive in Code
Being Expressive in Code
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java
 
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJSeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
 
Dynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner TypingDynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner Typing
 
Lecture 5 Inheritance
Lecture 5 InheritanceLecture 5 Inheritance
Lecture 5 Inheritance
 
Intake 37 6
Intake 37 6Intake 37 6
Intake 37 6
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 

Similar a Encoding numbers in μ-Java using successor and zero types

C C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.inC C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.inTIB Academy
 
The Next Mainstream Programming Language: A Game Developer’s Perspective
The Next Mainstream Programming Language: A Game Developer’s PerspectiveThe Next Mainstream Programming Language: A Game Developer’s Perspective
The Next Mainstream Programming Language: A Game Developer’s Perspectiveguest4fd7a2
 
Tim Popl
Tim PoplTim Popl
Tim Poplmchaar
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the BasicsJussi Pohjolainen
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5Ismar Silveira
 
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
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scalaparag978978
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasicswebuploader
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Sachin Singh
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpSatish Verma
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 
JavaScript Foundations Day1
JavaScript Foundations Day1JavaScript Foundations Day1
JavaScript Foundations Day1Troy Miles
 

Similar a Encoding numbers in μ-Java using successor and zero types (20)

C tutorial
C tutorialC tutorial
C tutorial
 
C C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.inC C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.in
 
The Next Mainstream Programming Language: A Game Developer’s Perspective
The Next Mainstream Programming Language: A Game Developer’s PerspectiveThe Next Mainstream Programming Language: A Game Developer’s Perspective
The Next Mainstream Programming Language: A Game Developer’s Perspective
 
Tim Popl
Tim PoplTim Popl
Tim Popl
 
C#
C#C#
C#
 
Rits Brown Bag - TypeScript
Rits Brown Bag - TypeScriptRits Brown Bag - TypeScript
Rits Brown Bag - TypeScript
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
core java
 core java core java
core java
 
Introduction to typescript
Introduction to typescriptIntroduction to typescript
Introduction to typescript
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasics
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
JavaScript Foundations Day1
JavaScript Foundations Day1JavaScript Foundations Day1
JavaScript Foundations Day1
 

Último

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Último (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Encoding numbers in μ-Java using successor and zero types

  • 1. A well-typed program never goes wrong julien@kaching.com Silicon Valley Code Camp 2010
  • 2. µ-Java Imagine Java deprived of all native types and all control-flow constructs
  • 3. Encoding ℕ in µ-Java A number is either zero or the successor of another number
  • 4. Encoding ℕ in µ-Java interface Number { } class Zero implements Number { } class Successor implements Number { privatefinal Number predecessor; Successor(Number predecessor) { this.predecessor = predecessor; } }
  • 5. Encoding ℕ in µ-Java Number zero = new Zero(); Number one = new Successor(zero); Number two = new Successor(one);
  • 6. Encoding ℕ in µ-Java Number zero = new Zero(); Number one = new Successor(zero); Number two = new Successor(one); Number three = one.plus(two);
  • 7. Encoding ℕ in µ-Java interface Number { Number plus(Number that); }
  • 8. Encoding ℕ in µ-Java class Zero implements Number { public Number plus(Number that) { } }
  • 9. Encoding ℕ in µ-Java class Zero implements Number { public Number plus(Number that) { return that; } }
  • 10. Encoding ℕ in µ-Java classSuccessor implementsNumber { privatefinal Number predecessor; Successor(Number predecessor) { this.predecessor = predecessor; } public Number plus(Number that) { } }
  • 11. Encoding ℕ in µ-Java classSuccessor implementsNumber { privatefinal Number predecessor; Successor(Number predecessor) { this.predecessor = predecessor; } public Number plus(Number that) { returnnew Successor(predecessor.plus(that)); } }
  • 12. Encoding ℕ in µ-Java Base case: 0 + n = n Recurrence: m + n = ((m - 1) + n) + 1
  • 13. Growing a Language µ-Java expressiveness
  • 14. Today’s Agenda Practical discussion of Type Safety. Grow your language to make it safer.
  • 15. “I’ve written well-typed programs before, and they went wrong!”
  • 16. This will definitely go wrong scala> defdivide(a: Int, b: Int) = a / b divide: (a: Int,b: Int)Int
  • 17. This will definitely go wrong scala> defdivide(a: Int, b: Int) = a / b divide: (a: Int,b: Int)Int scala> divide(4, 0) java.lang.ArithmeticException: / by zero at .divide(<console>:5)
  • 19. Was it well-typed? Yes, but the types didn’t fully convey the complexity of the domain. The type checker doesn’t know you can’t divide by 0 unless it is expressed by the types. How can you grow the language to address this issue?
  • 20. Division by zero, revisited scala> abstractclass Number(n: Int) scala> caseclass Zero extends Number(0) scala> caseclassNonZero(n: Int) extends Number(n) scala> def number(n: Int) = if (n == 0) Zero elseNonZero(n)
  • 21. Division by zero, revisited scala> abstractclass Number(n: Int) { def divide(that: NonZero) = number(n / that.n) } scala> number(4).divide(Zero)
  • 22. Division by zero, revisited scala> abstractclass Number(n: Int) { def divide(that: NonZero) = number(n / that.n) } scala> number(4).divide(Zero) error: type mismatch; found : Zero required: NonZero
  • 23. Type Safety The extent to which a programming language discourages or prevents type errors. A type error is erroneous program behavior caused by a discrepancy between differing data types.
  • 24. Well-typed programs never go wrong Preservation Well typednessof programs remains invariant under the transition rules of the language. Progress A well typed program never gets into a state where no further transitions are possible.
  • 25. Value Types Represents possibly infinite set of similarly kinded data transcending an application's life. Life cycles are meaningless. Value types are immutable. Usually restrict the universe of their underlying types.
  • 26. Value Types classEmailAddressextends Value<String> { … classPrice extends Value<Long> { … class Id<E extends Entity> extends Value<Long> { …
  • 27. The 1:1 Principle booleanplaceLimitOrder(Action, Integer, String, Long); booleanplaceLimitOrder(Action, Quantity, Ticker, Price);
  • 28. Type Safe Bit Field Apple's ticker AAPL. What about Berkshire Hathaway’s? Google says BRKA, Yahoo! BRK-A, Bloomberg BRK/A and Reuters BRKa.
  • 29. Type Safe Bit Field interfaceSecurityTag {   interfaceGoogle extendsSecurityTag{}   interfaceYahoo extendsSecurityTag{}   interfaceBloomberg extendsSecurityTag{}   interfaceReuters extendsSecurityTag{} }
  • 30. Type Safe Bit Field classTaggedTicker<T extendsSecurityTag> extends Value<String> { ...
  • 31. Type Safe Bit Field Price getPriceFromGoogle( TaggedTicker<Google> ticker) { ...   voidsendBuyOrderToBloomberg( TaggedTicker<Bloomberg> ticker, Quantity quantity) { ..
  • 32. Type Safe Bit Field interface Security { <T extendsSecurityTag> TaggedTicker<T> getTaggedTicker(Class<T> kind); }
  • 33. Type Safe Bit Field Map<Class<? extendsSecurityTag>, Long> TAG2MASK = ImmutableMap. <Class<? extendsSecurityTag>, Long> builder()      .put(SecurityTag.Google.class, 0x01)      .put(SecurityTag.Yahoo.class, 0x02)      .put(SecurityTag.Bloomberg.class, 0x04)      .put(SecurityTag.Reuters.class, 0x08)      .build();
  • 34. Type Safe Bit Field <T extendsSecurityTag> void set(Class<T> kind) { tags = (tags | TAG2MASK.get(kind)); } <T extendsSecurityTag> void unset(Class<T> kind) { tags = (tags & ~TAG2MASK.get(kind)); }
  • 35. Invariant Map A bunch of methods in java.util.Map are contravariant on the key type. This makes refactorings extremely error prone. java.util.Map#get(Object) java.util.Map#remove(Object) java.util.Map#containsKey (Object)
  • 36. Invariant Map voiddoSomething(Map<Ticker, Quote> cache) { … cache.remove(ticker);
  • 37. Invariant Map voiddoSomething(Map<Isin, Quote> cache) { … cache.remove(ticker);
  • 38. Invariant Map interfaceInvariantMap<K, V> { V get(K key); V remove(K key); ...
  • 39. Invariant Map classInvariantMaps{ static<K, V> InvariantMap<K, V> newHashMap() { returndelegate(newHashMap<K, V>()); } static<K extends Comparable<? super K>, V> InvariantMap<K, V> newTreeMap() { returndelegate(newTreeMap<K, V>()); } …
  • 40. Option abstractclass Option[T] caseclass None extends Option[Nothing] caseclass Some(x: T) extends Option[T] getUser(id) match { case Some(user) ⇒ … case None ⇒ … }
  • 41. Option Much more verbose in Java... getUser(id).visit(newOptionVisitor<Unit>() { public Unit caseSome(User user) { … publicUnit caseNone() { … })
  • 42. Option … but still useful! interfaceUserRepository { Option<User> getUser(Id<User> id); User getUserOrThrow(Id<User> id); }
  • 43. Abstracting the Control Flow We saw how to grow a language by introducing more types. We can also improve control flow structuresby abstracting the control flow.
  • 44. Abstracting the Control Flow BigDecimal total = ZERO; for (BigDecimal value : values) { if (value.compareTo(ZERO) > 0) { total.add(value); } } return total;
  • 45. Abstracting the Control Flow returnsum(filter( values, new Predicate<BigDecimal>() { publicboolean apply(BigDecimal t) { return t.compareTo(ZERO) > 0; } }));
  • 46. Abstracting the Control Flow Easier to re-use operations. The “wiring” between operations is checked by the type system.
  • 47. References Foundations for Programming Languages John C. Mitchell I Can Has Invariant Mapz? http://eng.kaching.com/2010/07/i-can-has-invariant-mapz.html Type Safe Bit Fields Using Higher-KindedPolymorphism http://eng.kaching.com/2010/08/type-safe-bit-fields-using-higher.html