SlideShare ist ein Scribd-Unternehmen logo
1 von 52
Downloaden Sie, um offline zu lesen
Protocols with
Associated Types
and how they got that way
(maybe)
 
@alexisgallagher
Protocols with Associated Pain
1. Hurray, I'm using value types!
2. Oh, I can't subclass.
3. Hurray, I'm using protocols!
4. Hurray, I'm adopting Equatable!
5.
Protocols with Associated Pain
Plain protocols, work as expected:
protocol MyProto {
}
struct Foo : MyProto {
}
let protoVar:MyProto = Foo() // <-- No problem!
Protocols with Associated Pain
Protocols with associated types, do not:
protocol MyProto {
typealias MyAssocType // declare requirement
}
struct Foo : MyProto {
typealias MyAssocType = Int // meet requirement
}
let protoVar:MyProto = Foo() // <-- Nope!
Protocols with Associated Pain
Protocols requiring Self? Same story:
protocol MyEquatable {
typealias MySelf // Self is a special associated type ...
}
struct Foo : MyEquatable {
typealias MySelf = Foo // ... always equal to adopting type
}
let protoVar:MyEquatable = Foo() // <-- Nope!
PATs are a bit weird
why ?
Comprendre c'est
pardonner
Questions
1. How are PATs weird?
2. Why are PATs weird?
3. Is this the plan?
4. How to love them?
How PATs are weird
W1. Only usable as generic constraints
Weirdness 1: only usable as generic constraints
• This rule excludes PATs from literally every single use of
"protocols" as defined in Objective-C
Weirdness 1: only usable as generic constraints
• This rule excludes PATs from literally every single use of
"protocols" as defined in Objective-C
• Everywhere you wanted a protocol, you need a generic:
   From:   var delegate:Proto
   To:        class C<T:Proto> { var delegate:T } }
Weirdness 1: only usable as generic constraints
• This rule excludes PATs from literally every single use of
"protocols" as defined in Objective-C
• Everywhere you wanted a protocol, you need a generic:
   From:   var delegates:[Proto]
   To:        class C<T:Proto> { var delegates:[T] } }
• Which still excludes dynamic dispatch … which might be
why you wanted a protocol to begin with!
How PATs are weird
W2. Docs describe them as "real" types
How PATs are weird
W3. The mysterious typealias
Weirdness 3: the mysterious typealias
typealias serves two different functions:
1. Outside PATs: provides the syntactic convenience of
meaningful names
2. Inside PATs, establishes a semantic requirement on types
adopting the PAT
Weirdness 3: the mysterious typealias
• typealias defines a placeholder for an unknown type ...
• ... which can be used throughout the protocol definition
protocol Animal {
typealias Food
func eat(food:Food) { }
}
This sounds familiar...
Weirdness 3: the mysterious typealias
typealias feels like a generic type parameter!
struct Animal<Food> {
func eat(food:Food) { }
}
protocol Animal {
typealias Food
func eat(food:Food) { }
}
Are PATs just generic protocols
with whacky syntax??
Does that explain everything?!
No
No
And yes, sort of
2. Why PATs are weird
The problem associated types solve
Subtyping alone cannot capture rich type relations
protocol Food { }
struct Grass : Food { }
protocol Animal {
func eat(f:Food)
}
struct Cow : Animal {
func eat(f:Grass) { } // <- error, Cow must eat Food
}
The problem associated types solve
Subtyping alone cannot capture rich type relations
protocol Food { }
struct Grass : Food { }
protocol Animal {
typealias Food
func eat(f:Food)
}
struct Cow { }
extension Cow : Animal {
func eat(f:Food) { } // <- OK
}
But why not use generic protocol syntax?
/// imaginary generic protocol swift
protocol Animal<Food> {
func eat(food:Food)
}
extension Cow : Animal<Grass> {
func eat(f:Grass) { }
}
But why not use generic protocol syntax?
• Because from outside the protocol, consumers could only
see the associated type by parameterizing over it:
/// generic-protocol-swift
func feedAnimal<A:Animal<F>,F>(a:A) {
// I see an F, and oh yeah F is a type variable for food
}
• But Swift PATs provide direct named access to associated
type, like properties
func feedAnimal<A:Animal>(a:A) {
// I see the assoc type: A.Food
}
But why not use generic protocol syntax?
And this problem compounds when protocols:
• have many associated types
• which might themselves be constrained by protocols
• and we want to use them all at once
Generic Graph BFS in Java (v 1.3)
public class breadth_first_search {
public static <
GraphT extends VertexListGraph<Vertex, VertexIterator, ?> &
IncidenceGraph<Vertex, Edge, OutEdgeIterator, ?>,
Vertex,
Edge extends GraphEdge<Vertex>,
VertexIterator extends Collection<Vertex>,
OutEdgeIterator extends Collection<Edge>,
ColorMap extends ReadWritePropertyMap<Vertex, ColorValue>,
Visitor extends BFSVisitor<GraphT, Vertex, Edge>>
void go(GraphT g, Vertex s, ColorMap c, Visitor vis);
}
Generic Graph BFS in C++
template <class G, class C, class Vis>
void breadth_first_search(const G& g,
typename graph traits<G>::vertex s, C c, Vis vis);
// constraints:
// G models Vertex List Graph and Incidence Graph
// C models Read/Write Map
// map traits<C>::key == graph traits<G>::vertex
// map traits<C>::value models Color
// Vis models BFS Visitor
Generic Graph BFS in Haskell (Hugs 2002)
breadth_first_search ::
(VertexListGraph g v, IncidenceGraph g e v,
ReadWriteMap c v Color, BFSVisitor vis a g e v) =>
g ! v ! c ! vis ! a ! a
3. Is this the plan?
Yes*
Two Worlds of Protocols
Without Self Requirement With Self Requirement
func precedes(other: Ordered) -> Bool func precedes(other: Self) -> Bool
Usable as a type
func sort(inout a: [Ordered])
Only usable as a generic constraint
func sort<T : Ordered>(inout a: [T])
Think“heterogeneous” Think“homogeneous”
Every model must deal with all others Models are free from interaction
Dynamic dispatch Static dispatch
Less optimizable More optimizable
* Existentials?
Comprendre c'est
pardonner
Questions
1. How are PATs weird?
2. Why are PATs weird?
3. Is this the plan?
4. How to love them?
Answers
How PATs are weird
• Lock you into generics and static dispatch
• typealias syntax plays two roles
• Associated type is as much like a required property as like a
type parameter
Answers
Why PATs are weird
• Rich, multi-type abstractions do not "fit" in OOP subtyping
• Designed to address known issues with naive "generic
protocol" designs (complexity scales badly with more
associated types)
Answers
Yes, functioning as planned
• Seems informed by C++ concepts, Haskell type classes, SML
signatures, generics in C# and Java, abstract type members
in Scala, etc.
• Impact on OOP "protocol" pattern: collateral damage
• Existentials?
4. How to love them?
Call them
PATs
Answers
How to love them
• Call them PATs
• Embrace generics
• If you still need dynamic dispatch
• use enums to push runtime variation into values
• use type erasure to hide dynamic dispatch within a type
• wait for existentials?
Protocols with
Associated Types
and how they got that way
(but now we can just ask on swift-evolution, right?)
 
@alexisgallagher

Weitere ähnliche Inhalte

Was ist angesagt?

Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE Saraswathi Murugan
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation xShahjahan Samoon
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlinSergey Bandysik
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Python for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comPython for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comShwetaAggarwal56
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaRasan Samarasinghe
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Twoamiable_indian
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming LanguageRaghavan Mohan
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Languagezone
 

Was ist angesagt? (20)

Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
DITEC - Programming with Java
DITEC - Programming with JavaDITEC - Programming with Java
DITEC - Programming with Java
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlin
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Java vs kotlin
Java vs kotlinJava vs kotlin
Java vs kotlin
 
Python ppt
Python pptPython ppt
Python ppt
 
Python
PythonPython
Python
 
Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
 
Python for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comPython for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.com
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Os Goodger
Os GoodgerOs Goodger
Os Goodger
 
python.ppt
python.pptpython.ppt
python.ppt
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
 

Andere mochten auch

Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CAlexis Gallagher
 
Data Sheet: Why Your eCommerce Platform Needs CIAM
Data Sheet: Why Your eCommerce Platform Needs CIAMData Sheet: Why Your eCommerce Platform Needs CIAM
Data Sheet: Why Your eCommerce Platform Needs CIAMGigya
 
How to Build a Strategic Talent Pipeline
How to Build a Strategic Talent Pipeline How to Build a Strategic Talent Pipeline
How to Build a Strategic Talent Pipeline Workology
 
COM 110: Chapter 1
COM 110: Chapter 1COM 110: Chapter 1
COM 110: Chapter 1Val Bello
 
Onderwijs voor iedereen met Khan Academy
Onderwijs voor iedereen met Khan AcademyOnderwijs voor iedereen met Khan Academy
Onderwijs voor iedereen met Khan AcademyYvonne Kleefkens
 
Unity歴0秒は何故ゲームジャムに飛び込んだのか
Unity歴0秒は何故ゲームジャムに飛び込んだのかUnity歴0秒は何故ゲームジャムに飛び込んだのか
Unity歴0秒は何故ゲームジャムに飛び込んだのかOkuno Kentaro
 
Foodborne Illnesses 101
Foodborne Illnesses 101Foodborne Illnesses 101
Foodborne Illnesses 101Food Insight
 
AJC 2011 Presentation - Building a Successful Marketing Strategy and Budget
AJC 2011 Presentation - Building a Successful Marketing Strategy and BudgetAJC 2011 Presentation - Building a Successful Marketing Strategy and Budget
AJC 2011 Presentation - Building a Successful Marketing Strategy and Budgetnkristy
 
Links as Language: A Contextual Approach to Content Creation
Links as Language: A Contextual Approach to Content CreationLinks as Language: A Contextual Approach to Content Creation
Links as Language: A Contextual Approach to Content CreationDavid Dylan Thomas
 
PR for CEO's: strategy and tips
PR for CEO's: strategy and tipsPR for CEO's: strategy and tips
PR for CEO's: strategy and tipsFINN
 
How PR Communicators Can Stay Relevant
How PR Communicators Can Stay RelevantHow PR Communicators Can Stay Relevant
How PR Communicators Can Stay RelevantThe Hoffman Agency
 
Guide to EV SSL certificate enrollment - by Comodo
Guide to EV SSL certificate enrollment - by ComodoGuide to EV SSL certificate enrollment - by Comodo
Guide to EV SSL certificate enrollment - by ComodoCheapSSLsecurity
 

Andere mochten auch (15)

Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
Open Lecture Peter Hilbers - July 8, 2016
Open Lecture Peter Hilbers - July 8, 2016Open Lecture Peter Hilbers - July 8, 2016
Open Lecture Peter Hilbers - July 8, 2016
 
Data Sheet: Why Your eCommerce Platform Needs CIAM
Data Sheet: Why Your eCommerce Platform Needs CIAMData Sheet: Why Your eCommerce Platform Needs CIAM
Data Sheet: Why Your eCommerce Platform Needs CIAM
 
How to Build a Strategic Talent Pipeline
How to Build a Strategic Talent Pipeline How to Build a Strategic Talent Pipeline
How to Build a Strategic Talent Pipeline
 
COM 110: Chapter 1
COM 110: Chapter 1COM 110: Chapter 1
COM 110: Chapter 1
 
theme1
theme1 theme1
theme1
 
Onderwijs voor iedereen met Khan Academy
Onderwijs voor iedereen met Khan AcademyOnderwijs voor iedereen met Khan Academy
Onderwijs voor iedereen met Khan Academy
 
Unity歴0秒は何故ゲームジャムに飛び込んだのか
Unity歴0秒は何故ゲームジャムに飛び込んだのかUnity歴0秒は何故ゲームジャムに飛び込んだのか
Unity歴0秒は何故ゲームジャムに飛び込んだのか
 
Foodborne Illnesses 101
Foodborne Illnesses 101Foodborne Illnesses 101
Foodborne Illnesses 101
 
AJC 2011 Presentation - Building a Successful Marketing Strategy and Budget
AJC 2011 Presentation - Building a Successful Marketing Strategy and BudgetAJC 2011 Presentation - Building a Successful Marketing Strategy and Budget
AJC 2011 Presentation - Building a Successful Marketing Strategy and Budget
 
Links as Language: A Contextual Approach to Content Creation
Links as Language: A Contextual Approach to Content CreationLinks as Language: A Contextual Approach to Content Creation
Links as Language: A Contextual Approach to Content Creation
 
Programma Nazionale per la Ricerca
Programma Nazionale per la RicercaProgramma Nazionale per la Ricerca
Programma Nazionale per la Ricerca
 
PR for CEO's: strategy and tips
PR for CEO's: strategy and tipsPR for CEO's: strategy and tips
PR for CEO's: strategy and tips
 
How PR Communicators Can Stay Relevant
How PR Communicators Can Stay RelevantHow PR Communicators Can Stay Relevant
How PR Communicators Can Stay Relevant
 
Guide to EV SSL certificate enrollment - by Comodo
Guide to EV SSL certificate enrollment - by ComodoGuide to EV SSL certificate enrollment - by Comodo
Guide to EV SSL certificate enrollment - by Comodo
 

Ähnlich wie Protocols with Associated Types, and How They Got That Way

Python for katana
Python for katanaPython for katana
Python for katanakedar nath
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & styleKevlin Henney
 
Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!Andreas Dewes
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developersMohamed Wael
 
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxStatic abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxMarco Parenzan
 
SOEN6441.generics.ppt
SOEN6441.generics.pptSOEN6441.generics.ppt
SOEN6441.generics.pptElieMambou1
 
C Types - Extending Python
C Types - Extending PythonC Types - Extending Python
C Types - Extending PythonPriyank Kapadia
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1Ahmet Bulut
 
Python Evolution
Python EvolutionPython Evolution
Python EvolutionQuintagroup
 
modul-python-part1.pptx
modul-python-part1.pptxmodul-python-part1.pptx
modul-python-part1.pptxYusuf Ayuba
 
Java Generics.ppt
Java Generics.pptJava Generics.ppt
Java Generics.pptbrayazar
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experiencedzynofustechnology
 
Moving to Python 3
Moving to Python 3Moving to Python 3
Moving to Python 3Nick Efford
 

Ähnlich wie Protocols with Associated Types, and How They Got That Way (20)

Generics
GenericsGenerics
Generics
 
Python for katana
Python for katanaPython for katana
Python for katana
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Python made easy
Python made easy Python made easy
Python made easy
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & style
 
ITFT - Java
ITFT - JavaITFT - Java
ITFT - Java
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!Type Annotations in Python: Whats, Whys and Wows!
Type Annotations in Python: Whats, Whys and Wows!
 
basics dart.pdf
basics dart.pdfbasics dart.pdf
basics dart.pdf
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
 
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxStatic abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
 
SOEN6441.generics.ppt
SOEN6441.generics.pptSOEN6441.generics.ppt
SOEN6441.generics.ppt
 
C Types - Extending Python
C Types - Extending PythonC Types - Extending Python
C Types - Extending Python
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
 
Python Evolution
Python EvolutionPython Evolution
Python Evolution
 
modul-python-part1.pptx
modul-python-part1.pptxmodul-python-part1.pptx
modul-python-part1.pptx
 
Python Tutorial for Beginner
Python Tutorial for BeginnerPython Tutorial for Beginner
Python Tutorial for Beginner
 
Java Generics.ppt
Java Generics.pptJava Generics.ppt
Java Generics.ppt
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experienced
 
Moving to Python 3
Moving to Python 3Moving to Python 3
Moving to Python 3
 

Kürzlich hochgeladen

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 

Kürzlich hochgeladen (20)

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 

Protocols with Associated Types, and How They Got That Way

  • 1. Protocols with Associated Types and how they got that way (maybe)   @alexisgallagher
  • 2. Protocols with Associated Pain 1. Hurray, I'm using value types! 2. Oh, I can't subclass. 3. Hurray, I'm using protocols! 4. Hurray, I'm adopting Equatable! 5.
  • 3.
  • 4. Protocols with Associated Pain Plain protocols, work as expected: protocol MyProto { } struct Foo : MyProto { } let protoVar:MyProto = Foo() // <-- No problem!
  • 5. Protocols with Associated Pain Protocols with associated types, do not: protocol MyProto { typealias MyAssocType // declare requirement } struct Foo : MyProto { typealias MyAssocType = Int // meet requirement } let protoVar:MyProto = Foo() // <-- Nope!
  • 6. Protocols with Associated Pain Protocols requiring Self? Same story: protocol MyEquatable { typealias MySelf // Self is a special associated type ... } struct Foo : MyEquatable { typealias MySelf = Foo // ... always equal to adopting type } let protoVar:MyEquatable = Foo() // <-- Nope!
  • 7. PATs are a bit weird why ?
  • 9. Questions 1. How are PATs weird? 2. Why are PATs weird? 3. Is this the plan? 4. How to love them?
  • 10. How PATs are weird W1. Only usable as generic constraints
  • 11. Weirdness 1: only usable as generic constraints • This rule excludes PATs from literally every single use of "protocols" as defined in Objective-C
  • 12. Weirdness 1: only usable as generic constraints • This rule excludes PATs from literally every single use of "protocols" as defined in Objective-C • Everywhere you wanted a protocol, you need a generic:    From:   var delegate:Proto    To:        class C<T:Proto> { var delegate:T } }
  • 13. Weirdness 1: only usable as generic constraints • This rule excludes PATs from literally every single use of "protocols" as defined in Objective-C • Everywhere you wanted a protocol, you need a generic:    From:   var delegates:[Proto]    To:        class C<T:Proto> { var delegates:[T] } } • Which still excludes dynamic dispatch … which might be why you wanted a protocol to begin with!
  • 14. How PATs are weird W2. Docs describe them as "real" types
  • 15.
  • 16. How PATs are weird W3. The mysterious typealias
  • 17. Weirdness 3: the mysterious typealias typealias serves two different functions: 1. Outside PATs: provides the syntactic convenience of meaningful names 2. Inside PATs, establishes a semantic requirement on types adopting the PAT
  • 18. Weirdness 3: the mysterious typealias • typealias defines a placeholder for an unknown type ... • ... which can be used throughout the protocol definition protocol Animal { typealias Food func eat(food:Food) { } } This sounds familiar...
  • 19. Weirdness 3: the mysterious typealias typealias feels like a generic type parameter! struct Animal<Food> { func eat(food:Food) { } } protocol Animal { typealias Food func eat(food:Food) { } }
  • 20. Are PATs just generic protocols with whacky syntax?? Does that explain everything?!
  • 21. No
  • 23. 2. Why PATs are weird
  • 24. The problem associated types solve Subtyping alone cannot capture rich type relations protocol Food { } struct Grass : Food { } protocol Animal { func eat(f:Food) } struct Cow : Animal { func eat(f:Grass) { } // <- error, Cow must eat Food }
  • 25. The problem associated types solve Subtyping alone cannot capture rich type relations protocol Food { } struct Grass : Food { } protocol Animal { typealias Food func eat(f:Food) } struct Cow { } extension Cow : Animal { func eat(f:Food) { } // <- OK }
  • 26. But why not use generic protocol syntax? /// imaginary generic protocol swift protocol Animal<Food> { func eat(food:Food) } extension Cow : Animal<Grass> { func eat(f:Grass) { } }
  • 27. But why not use generic protocol syntax? • Because from outside the protocol, consumers could only see the associated type by parameterizing over it: /// generic-protocol-swift func feedAnimal<A:Animal<F>,F>(a:A) { // I see an F, and oh yeah F is a type variable for food } • But Swift PATs provide direct named access to associated type, like properties func feedAnimal<A:Animal>(a:A) { // I see the assoc type: A.Food }
  • 28. But why not use generic protocol syntax? And this problem compounds when protocols: • have many associated types • which might themselves be constrained by protocols • and we want to use them all at once
  • 29. Generic Graph BFS in Java (v 1.3) public class breadth_first_search { public static < GraphT extends VertexListGraph<Vertex, VertexIterator, ?> & IncidenceGraph<Vertex, Edge, OutEdgeIterator, ?>, Vertex, Edge extends GraphEdge<Vertex>, VertexIterator extends Collection<Vertex>, OutEdgeIterator extends Collection<Edge>, ColorMap extends ReadWritePropertyMap<Vertex, ColorValue>, Visitor extends BFSVisitor<GraphT, Vertex, Edge>> void go(GraphT g, Vertex s, ColorMap c, Visitor vis); }
  • 30. Generic Graph BFS in C++ template <class G, class C, class Vis> void breadth_first_search(const G& g, typename graph traits<G>::vertex s, C c, Vis vis); // constraints: // G models Vertex List Graph and Incidence Graph // C models Read/Write Map // map traits<C>::key == graph traits<G>::vertex // map traits<C>::value models Color // Vis models BFS Visitor
  • 31. Generic Graph BFS in Haskell (Hugs 2002) breadth_first_search :: (VertexListGraph g v, IncidenceGraph g e v, ReadWriteMap c v Color, BFSVisitor vis a g e v) => g ! v ! c ! vis ! a ! a
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38. 3. Is this the plan? Yes*
  • 39. Two Worlds of Protocols Without Self Requirement With Self Requirement func precedes(other: Ordered) -> Bool func precedes(other: Self) -> Bool Usable as a type func sort(inout a: [Ordered]) Only usable as a generic constraint func sort<T : Ordered>(inout a: [T]) Think“heterogeneous” Think“homogeneous” Every model must deal with all others Models are free from interaction Dynamic dispatch Static dispatch Less optimizable More optimizable
  • 40.
  • 41.
  • 43.
  • 45. Questions 1. How are PATs weird? 2. Why are PATs weird? 3. Is this the plan? 4. How to love them?
  • 46. Answers How PATs are weird • Lock you into generics and static dispatch • typealias syntax plays two roles • Associated type is as much like a required property as like a type parameter
  • 47. Answers Why PATs are weird • Rich, multi-type abstractions do not "fit" in OOP subtyping • Designed to address known issues with naive "generic protocol" designs (complexity scales badly with more associated types)
  • 48. Answers Yes, functioning as planned • Seems informed by C++ concepts, Haskell type classes, SML signatures, generics in C# and Java, abstract type members in Scala, etc. • Impact on OOP "protocol" pattern: collateral damage • Existentials?
  • 49. 4. How to love them?
  • 51. Answers How to love them • Call them PATs • Embrace generics • If you still need dynamic dispatch • use enums to push runtime variation into values • use type erasure to hide dynamic dispatch within a type • wait for existentials?
  • 52. Protocols with Associated Types and how they got that way (but now we can just ask on swift-evolution, right?)   @alexisgallagher