SlideShare uma empresa 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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#
 

Semelhante 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
 

Semelhante 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

Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
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
 

Último (20)

Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
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...
 

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