SlideShare a Scribd company logo
1 of 53
Download to read offline
TypesAreEatingTheWorld!
AboutMyself
MynameisDaisukeShimamoto
Pronounced"Dice-K"
Twitter/Facebook/LinkedIn:@diskshima
Current:
EngineerManageratPROGRIT(aEnglish
coachingcompany)
PastExperience:
USInvestmentBank:Java&Spring,C#&.Net
Variousstart-ups:RubyonRails,React.js,React
Native,etc.
Me&Types
FascinatedbyTypesinprogramming.
Justfindtheminteresting.
IwriteHaskellasahobby.
Notusingittodaysopleasedon'trunaway
BeforeWeStart
WillbemainlyusingTypeScriptandSwiftinthistalk.
GoodsupportforTypes.
Notcovering/using
TypeTheory
Monads
Weirdgreeksymbols(ɑ,𝛽,𝛾,𝜎,𝜋,etc.)
Soagain,pleasedon'trunaway
KeyTakeaway:Typesarebecomingmoreimportant!
WhySo?
Softwareisbecoming:
Moreandmoreadvanced
Largerandlarger
Moreandmorecomplex
Whichleadsto...
Whichleadsto... MOREBUGS!!
Whatcanwedo?
Whatcanwedo?TYPES!!
StartwithBasics
BasicTypes
int
-1,0,1,2,3,...
float
0.1,0.25,0.3,...
char
'a','b','c',...
string
"hello","world",...
AdvancedTypes
FunctionTypes
number => string :Takesinanintandreturnsastring
const f: ((n: number) => string) = function (n) {

// Do something with n.

:

return "foo";

}

Generics(Java,C#,TypeScript,etc)
function firstElement<T>(arr: T[]): T {

return arr[0];

}
ButTypescandomore!
ButTypescandomore!
Let'slookatsomefairlynew/advancedTypes!
Optional
Indicatesthatthevaluecouldbe null .
You'veseenoneofthese,right?
java.lang.NullPointerException
TypeError: ‘undefined’ is not an object
Optionalspreventthis.
Example(Swift):
let num: Optional<Int> = function_that_may_return_nil()

if let a = num { // Take the Int inside Optional<Int>.

print(a)

} else {

print("Was nil")

}
Optional
Thecompilercancheckthatyou'veactuallyhandledthecaseof null .
Someexamplesinotherlanguages:
Java: Optional
C#: Nullable
Kotlin: Nullable
FunFactabout null
null wasfirstintroducedbyTonyHoare(famousComputerScientist).
Andhelaterreferredtoitasthebillion-dollarmistake
Icallitmybillion-dollarmistake.Itwastheinventionofthenullreferencein1965(in
ALGOLW).
Wikipedia
Async/Await,Future,Promise
Thesearetype(orlanguage)featureforhandlingasynchronousexecutions.
Example(TypeScript):
function delayedPrint(msg: string, delay: number): Promise<void> {

return new Promise((resolve, reject) => {

setTimeout(() => {

console.log(msg);
resolve();

}, delay);

});

}

async function main() {

console.log("Dispatching first delayedPrint.")

delayedPrint("Hello", 1000);

console.log("Dispatching second delayedPrint.")

await delayedPrint("Hello2", 1500);

console.log("This console.log will wait for the one above.")

delayedPrint("Hello3", 1000);

}

main();
Output:
Dispatching first delayedPrint.

Dispatching second delayedPrint.

Hello

Hello2

This console.log will wait the one above.

Hello3
Async/Await,Future,Promise
Intuitive
Comparedtothecallbackhell.
SupportedbyC#,TypeScript,Kotlin,etc.
BeingaddedtootherlanguageslikeSwift,C++.
Tellshowmuchengineerslovethisfeature
QuickSummarySoFar
Typesareeatingtheworld
Advancesinprogramminglanguagesarespeedinguplikecrazy.
Muchslowerintheolddays(RememberPerl6?C++0x)?)
TranspilerslikeBabelhashelpedalot.
ButTypescandoEVENMORE!
ButTypescandoEVENMORE!
Let'slookatsomemoreadvancedTypesthatwemayseeinthefuture.
1.AlgebraicDataTypes
1.AlgebraicDataTypes
Representsrelationshipsbetweendata.
Consistsoftwokinds:
SumType
Alsocalled"enum".
ThedatacouldbeoneofA,B,C...
ProductType
ThedatacanholdanelementofAandanelementofBandsoon.
Alsocalled"struct","record".
ExampleofSumType(inTypeScript)
interface A {

:

}

interface B {

:

}

type A_OR_B = A | B; // Meaning it can be either A or B
ExampleofProductTypeinSwift:
struct ProductExample {

let a: Bool

let b: Bool

}
UseCases
TypeScriptExample
interface Square {

kind: "square";

size: number;

}

interface Rectangle {

kind: "rectangle";

width: number;

height: number;

}

type Shape = Square | Rectangle; // Either a Square or a Rectangle.
TypeScriptExample(cont'd)
function non_exhaustive(s: Shape) {

switch (s.kind) {

case "square":

return s.size * s.size;

default:

const _tmp: never = s

// ^^^^ This is a compile time error!

}

return 0;

}

function not_in_part_of_the_type(s: Shape) {

switch (s.kind) {

case "square": return s.size * s.size;

case "rectangle": return s.height * s.width;

case "circle": return s.height;

// ^^^^^^^^ This is a compile time error!

}

}
Obvious?Yes.
Somelanguagesdonotnotsupportthisorhavenotfullysupportedthem.
PHPProposal:PHP:rfc:adts
Kotlin:Supportsealed(exhaustive)whens
Compiletimecheckofexhaustivenessofsumtypes.
Why"Algebraic"?
Somethingtodowithmathbutwon'tgodeepertoday.
Irecommendreading:
Thealgebra(andcalculus!)ofalgebraicdatatypes
2.DependentTypes
DependentTypes
AllTypessofar
MakeacleardistinctionbetweenTypesandValues
Valuesdependontheirtypes
const num: int = 1; // <-- 1 depends on int.

const str: string = "hello"; // <-- "hello" depends on string.
Canwenotflipthis?
i.e.haveTypesdependonValues?
What??
Let'sstartwithaproblemwewanttosolve.
Problem:"Functionthatexpectsevennumbers"
Problem:"Functionthatexpectsevennumbers"
NormalTypeScript:
function f(n: int) {
if (n % 2 != 0) {

throw "n is not even!"

} else {

// n is even.

// Do something with n.

:

}

}

f(1) // Compiler will be happy but will definitely THROW!
IntroducingDependentTypes
DependentTypesallowyoutousevaluesinthetypes.
// This is made-up syntax. Doesn't actually work!

function f(n: { int | n % 2 == 0 }) {

// ^^^^^^^^^^ Compile time check!

:

}

f(1) // Compiler will error!
DependentTypes
EncodesmorelogicintotheType.
Morecompiletimechecks!
ByauseronStackoverflow:
Dependenttypesenablelargersetoflogicerrorstobeeliminatedatcompile
time.
DependentTypes
Notmuchsupportyet
Onlyafewlanguagessupportit:
Agda
Idris
Let'sseeifmainstreamlanguagesadoptit
3.LinearTypes
3.LinearTypes
Againlet'sstartwiththeproblem.
Problem:"Howcanwepreventuseofvariableswhen
theyshouldnotbeused?"
Problem:"Howcanwepreventuseofvariableswhen
theyshouldnotbeused?"
Examples:
Useafter free .
Double free .
Accessingaclosedfilehandler.
IntroducingLinearTypes
LinearTypesmustbeusedonceandonlyonce.
Thekeyismustandonce.
UseCases#1
Linearresources
Files,networksockets,etc.
// Again made-up syntax. Does not actually work.

linearfunc readFile(filepath: string): string {

const fileHandle = open(filepath);

const content = readFile(fileHandle);

return content;

// Oops! Forgot to close `fileHandle`! 

// Compiler can automatically emit, operation to close the handle.

}
UseCase#2
Performance
Ifyouknowitwon'tbeused,youcanoptimizeit.
// Again made-up syntax. TypeScript does not have this!

linearfunc f(str: string): string {

const str2 = str + "aaaaaa"; // Plain TypeScript will allocate a new memory for this.

return str2; // <- The compiler can make a decision and overwrite str in memory for performance!

}
Summary
SomerecentTypesseeninmainstreamlanguages.
Optional
Await/Async,Future,Promise
MoreAdvancedTypes
AlgebraicDataTypes
DependentTypes
LinearTypes
Thanks!
Attributions
HaskellIcon:https://icon-icons.com/icon/file-type-haskell/130552
SwiftIcon:https://icon-icons.com/icon/swift-original-logo/146332
TypeScriptIcon:https://icon-icons.com/icon/file-type-typescript-official/130107

More Related Content

Similar to Types are eating the world

OWASP PHPIDS talk slides
OWASP PHPIDS talk slidesOWASP PHPIDS talk slides
OWASP PHPIDS talk slides
guestd34230
 

Similar to Types are eating the world (20)

Future of Ruby on the Web
Future of Ruby on the WebFuture of Ruby on the Web
Future of Ruby on the Web
 
Managing JavaScript Complexity
Managing JavaScript ComplexityManaging JavaScript Complexity
Managing JavaScript Complexity
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
 
Sorbet at Grailed
Sorbet at GrailedSorbet at Grailed
Sorbet at Grailed
 
OWASP PHPIDS talk slides
OWASP PHPIDS talk slidesOWASP PHPIDS talk slides
OWASP PHPIDS talk slides
 
DSLs in JavaScript
DSLs in JavaScriptDSLs in JavaScript
DSLs in JavaScript
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
 
Beyond the Style Guides
Beyond the Style GuidesBeyond the Style Guides
Beyond the Style Guides
 
Grooming with Groovy
Grooming with GroovyGrooming with Groovy
Grooming with Groovy
 
RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!
 
Goodparts
GoodpartsGoodparts
Goodparts
 
Migrating Web SDK from JS to TS
Migrating Web SDK from JS to TSMigrating Web SDK from JS to TS
Migrating Web SDK from JS to TS
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
 
TechDays - IronRuby
TechDays - IronRubyTechDays - IronRuby
TechDays - IronRuby
 
Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987
 
Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...
 
Lagergren jvmls-2013-final
Lagergren jvmls-2013-finalLagergren jvmls-2013-final
Lagergren jvmls-2013-final
 
Complete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptComplete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScript
 
Ruby for .NET developers
Ruby for .NET developersRuby for .NET developers
Ruby for .NET developers
 
Dear compiler please don't be my nanny v2
Dear compiler  please don't be my nanny v2Dear compiler  please don't be my nanny v2
Dear compiler please don't be my nanny v2
 

More from Fangda Wang

More from Fangda Wang (11)

[WWCode] How aware are you of your deciding model?
[WWCode] How aware are you of your deciding model?[WWCode] How aware are you of your deciding model?
[WWCode] How aware are you of your deciding model?
 
Under the hood of architecture interviews at indeed
Under the hood of architecture interviews at indeedUnder the hood of architecture interviews at indeed
Under the hood of architecture interviews at indeed
 
How Indeed asks coding interview questions
How Indeed asks coding interview questionsHow Indeed asks coding interview questions
How Indeed asks coding interview questions
 
From ic to tech lead
From ic to tech leadFrom ic to tech lead
From ic to tech lead
 
Introduction to japanese tokenizer
Introduction to japanese tokenizerIntroduction to japanese tokenizer
Introduction to japanese tokenizer
 
Gentle Introduction to Scala
Gentle Introduction to ScalaGentle Introduction to Scala
Gentle Introduction to Scala
 
To pair or not to pair
To pair or not to pairTo pair or not to pair
To pair or not to pair
 
Balanced Team
Balanced TeamBalanced Team
Balanced Team
 
Functional programming and Elm
Functional programming and ElmFunctional programming and Elm
Functional programming and Elm
 
Elm at large (companies)
Elm at large (companies)Elm at large (companies)
Elm at large (companies)
 
Data science tools of the trade
Data science tools of the tradeData science tools of the trade
Data science tools of the trade
 

Recently uploaded

Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 

Recently uploaded (20)

CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 

Types are eating the world