SlideShare une entreprise Scribd logo
1  sur  28
Télécharger pour lire hors ligne
Linear Types in Haskell
David Overton
Melbourne Haskell Users Group - July 2020
1
Linear types can change the
world!
— Philip Wadler, 1990
2
Outline
— Motivation
— What are linear types?
— Proposed GHC extension
— Linear base library
— Trying it out
— Examples
— Related work
— Time for questions / discussion / hacking
3
Motivation
Linear types make using resources safer and more predictable:
— Safe malloc/free memory management
— Safe usage of file handles - closed exactly once, not used
after close
— Safe mutable arrays - destructive update
— Safer inlining and guaranteed fusion
— Session types
4
What are Linear Types?
5
Linearity
— A function f is linear when
if f u is consumed exactly once
then u is consumed exactly once
— Consuming a value of a data type exactly once means
evaluating it to head normal form exactly once,
discriminating on its tag any number of times, then
consuming its fields exactly once.
— Consuming a function exactly once means applying it and
conuming its result exactly once.
6
Proposed GHC extension
7
Basic syntax
A #-> B
is the type of linear functions from A to B.
— In papers often written (from Linear Logic).
— Alternative (rejected) proposals:
— A -o B
— A ->. B
8
Simple examples
-- Valid:
const :: a -> b -> a
const a _ = a
-- Valid:
const :: a #-> b -> a
-- Not valid:
const :: a -> b #-> a
-- Not valid:
dup :: a #-> (a, a)
dup x = (x, x)
9
Algebraic data types
Most "normal" data types will have linear constructors. E.g.
data Maybe a
= Nothing
| Just a
is equivalent to
data Maybe a where
Nothing :: Maybe a
Just :: a #-> Maybe a
10
Unrestricted
Explicitly unrestricted or non-linear constructor using
GADT syntax:
data Unrestricted a where
Unrestricted :: a -> Unrestricted a
11
Polymorphism
Two possible types of map:
map :: (a -> b) -> [a] -> [b]
map :: (a #-> b) -> [a] #-> [b]
— The map function preserves the multiplicity of its
function argument
— But we don't want to have to define it twice
12
Polymorphism
To avoid code duplication, functions can have
multipicity polymorphism.
map :: (a #p-> b) -> [a] #p-> [b]
where p is a multiplicity parameter.
— Linear functions have multiplicity or One
— Unrestricted functions have multiplicity or Many
13
Multiple multiplicities
(.) :: (b #p-> c) -> (a #q-> b) -> a #(p ':* q)-> c
would require 4 different types without polymorphism:
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) :: (b #-> c) -> (a -> b) -> a -> c
(.) :: (b -> c) -> (a #-> b) -> a -> c
(.) :: (b #-> c) -> (a #-> b) -> a #-> c
— (p ':* q) multiplies the multiplicies p and q:
14
Details
data Multiplicity = One | Many
-- Type families
type family (:+) (p :: Multiplicity) (q :: Multiplicity) :: Multiplicity
type family (:*) (p :: Multiplicity) (q :: Multiplicity) :: Multiplicity
-- New type constructor
FUN :: Multiplicity -> forall (r1 r2 :: RuntimeRep). TYPE r1 -> TYPE r2
-- FUN p a b ~ a #p-> b
type (->) = FUN 'Many
type (#->) = FUN 'One
15
Linear base library
16
Linear base library
https://github.com/tweag/linear-base
Needed to write anything useful with linear types
Provides:
— Linear Prelude
— Linear arrays
— Linear I/O
— ...
17
Trying it out
18
Trying it out
— GHC 8.11 has a partial implementation of -XLinearTypes
— Missing support for where and let
— Missing support for multiplicity polymorphism
— Probably missing other stuff too
— GHC 9.0.1 will have more complete support, but still considered
"experimental"
— Due for release in September 2020
— linear-base library has instructions for setting up a Stack project
with GHC 8.11 and linear-base using nix
19
Examples
20
I/O
-- Ensures I/O state is linearly threaded, meaning it is safe to
-- expose the IO constructor
newtype IO a = IO (State# RealWorld #-> (# State# RealWorld, a #))
-- Resource-aware IO monad (equivalent of ResourceT IO)
newtype RIO a = RIO (IORef ReleaseMap -> Linear.IO a)
-- Note: non-linear
openFile :: FilePath -> System.IOMode -> RIO Handle
-- hClose consumes the handle so it can't be used again after it's closed.
hClose :: Handle #-> RIO ()
-- Other I/O operations must also be linear with respect to handle
-- meaning each operation needs to return a new handle.
hPutChar :: Handle #-> Char -> RIO Handle
hGetChar :: Handle #-> RIO (Unrestricted Char, Handle)
21
I/O
linearGetFirstLine :: FilePath -> RIO (Unrestricted Text)
linearGetFirstLine fp = do
handle <- Linear.openFile fp System.ReadMode
(t, handle') <- Linear.hGetLine handle
Linear.hClose handle'
return t
where
Control.Builder {..} = Control.monadBuilder
linearPrintFirstLine :: FilePath -> System.IO ()
linearPrintFirstLine fp = do
text <- Linear.run (linearGetFirstLine fp)
System.putStrLn (unpack text)
Excercise:
— What happens if we forget to close the file handle?
— Use the handle more than once?
— Use after close?
22
Mutable arrays
fromList :: [a] -> (Array a #-> Unrestricted b) -> Unrestricted b
toList :: Array a #-> (Array a, [a])
length :: Array a #-> (Array a, Int)
write :: Array a #-> Int -> a -> Array a
read :: Array a #-> Int -> (Array a, Unrestricted a)
— Note use of continuation passing style for fromList
— Required to ensure that the array is always used linearly
— Operations return a "new" array
Excercise:
— Write a function to swap two elements in an array.
23
void swap(int a[], int i, int j) {
int t = a[i];
int u = a[j]
a[i] = u;
a[j] = t;
}
swap :: Array a #-> Int -> Int -> Array a
swap a i j =
Array.read a i & case
(a', Unrestricted t) -> Array.read a' j & case
(a'', Unrestricted u) -> Array.write a'' i u &
a''' -> Array.write a''' j t
24
Related Work
25
— Linear Types Can Change the World!, Philip Wadler, 1990
— Based on Linear Logic
— Linearity on types rather than functions
— Clean
— Uniqueness types - "I have the only unique reference to this object"
— Used for I/O state
— Mercury
— Uniqueness using modes
— Rust
— Ownership and borrowing have similarites to uniqueness and
linearity, respectively
26
The Linearity Design Space1
Linearity on the
arrows
Linearity on the
kinds
Linear types Linear Haskell Rust (borrowing)
Uniqueness types Rust (ownership),
Clean, Mercury
(modes)
1 
Taken from SPJ's talk
27
References
— Linear Haskell - Practical Linearity in a Higher-Order
Polymorphic Langauge, Bernardy et al, Nov 2017.
— GHC Proposal
— Linear Base Library
— Examples
— Simon Peyton Jones - Linear Haskell: practical linearity in a
higher-order polymorphic language
— Linear types can change the world! - Philip Wadler, 1990
28

Contenu connexe

Tendances

Unix Shell Scripting
Unix Shell ScriptingUnix Shell Scripting
Unix Shell ScriptingMustafa Qasim
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++imran khan
 
Storage classes in c++
Storage classes in c++Storage classes in c++
Storage classes in c++Jaspal Singh
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationWei-Ren Chen
 
Beyond printk: Efficient Zynq UltraScale+ MPSoC Linux Debugging and Development
Beyond printk: Efficient Zynq UltraScale+ MPSoC Linux Debugging and DevelopmentBeyond printk: Efficient Zynq UltraScale+ MPSoC Linux Debugging and Development
Beyond printk: Efficient Zynq UltraScale+ MPSoC Linux Debugging and DevelopmentZach Pfeffer
 
LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)Wang Hsiangkai
 
Effective service and resource management with systemd
Effective service and resource management with systemdEffective service and resource management with systemd
Effective service and resource management with systemdDavid Timothy Strauss
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsDhivyaSubramaniyam
 
3.looping(iteration statements)
3.looping(iteration statements)3.looping(iteration statements)
3.looping(iteration statements)Hardik gupta
 
An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)
An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)
An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)William Liang
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrencyxu liwei
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphismlalithambiga kamaraj
 
Linux binary Exploitation - Basic knowledge
Linux binary Exploitation - Basic knowledgeLinux binary Exploitation - Basic knowledge
Linux binary Exploitation - Basic knowledgeAngel Boy
 

Tendances (20)

Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Unix Shell Scripting
Unix Shell ScriptingUnix Shell Scripting
Unix Shell Scripting
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++
 
Linux Commands
Linux CommandsLinux Commands
Linux Commands
 
Decision Making and Looping
Decision Making and LoopingDecision Making and Looping
Decision Making and Looping
 
Storage classes in c++
Storage classes in c++Storage classes in c++
Storage classes in c++
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
 
Beyond printk: Efficient Zynq UltraScale+ MPSoC Linux Debugging and Development
Beyond printk: Efficient Zynq UltraScale+ MPSoC Linux Debugging and DevelopmentBeyond printk: Efficient Zynq UltraScale+ MPSoC Linux Debugging and Development
Beyond printk: Efficient Zynq UltraScale+ MPSoC Linux Debugging and Development
 
LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)
 
Effective service and resource management with systemd
Effective service and resource management with systemdEffective service and resource management with systemd
Effective service and resource management with systemd
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
functions of C++
functions of C++functions of C++
functions of C++
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
3.looping(iteration statements)
3.looping(iteration statements)3.looping(iteration statements)
3.looping(iteration statements)
 
An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)
An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)
An introduction to the linux kernel and device drivers (NTU CSIE 2016.03)
 
Python Control Structures.pptx
Python Control Structures.pptxPython Control Structures.pptx
Python Control Structures.pptx
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrency
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Linux binary Exploitation - Basic knowledge
Linux binary Exploitation - Basic knowledgeLinux binary Exploitation - Basic knowledge
Linux binary Exploitation - Basic knowledge
 

Similaire à Linear Types in Haskell

Groovy presentation
Groovy presentationGroovy presentation
Groovy presentationManav Prasad
 
C standard library functions
C standard library functionsC standard library functions
C standard library functionsVaishnavee Sharma
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
Overview of Chainer and Its Features
Overview of Chainer and Its FeaturesOverview of Chainer and Its Features
Overview of Chainer and Its FeaturesSeiya Tokui
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法x1 ichi
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkAngelo Leto
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and FuturePushkar Kulkarni
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present FutureIndicThreads
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hotSergii Maliarov
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play frameworkFelipe
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyTypesafe
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packagesAjay Ohri
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
 

Similaire à Linear Types in Haskell (20)

Java 8
Java 8Java 8
Java 8
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
C standard library functions
C standard library functionsC standard library functions
C standard library functions
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Overview of Chainer and Its Features
Overview of Chainer and Its FeaturesOverview of Chainer and Its Features
Overview of Chainer and Its Features
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with spark
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packages
 
Java8
Java8Java8
Java8
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 

Dernier

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 

Dernier (20)

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 

Linear Types in Haskell

  • 1. Linear Types in Haskell David Overton Melbourne Haskell Users Group - July 2020 1
  • 2. Linear types can change the world! — Philip Wadler, 1990 2
  • 3. Outline — Motivation — What are linear types? — Proposed GHC extension — Linear base library — Trying it out — Examples — Related work — Time for questions / discussion / hacking 3
  • 4. Motivation Linear types make using resources safer and more predictable: — Safe malloc/free memory management — Safe usage of file handles - closed exactly once, not used after close — Safe mutable arrays - destructive update — Safer inlining and guaranteed fusion — Session types 4
  • 5. What are Linear Types? 5
  • 6. Linearity — A function f is linear when if f u is consumed exactly once then u is consumed exactly once — Consuming a value of a data type exactly once means evaluating it to head normal form exactly once, discriminating on its tag any number of times, then consuming its fields exactly once. — Consuming a function exactly once means applying it and conuming its result exactly once. 6
  • 8. Basic syntax A #-> B is the type of linear functions from A to B. — In papers often written (from Linear Logic). — Alternative (rejected) proposals: — A -o B — A ->. B 8
  • 9. Simple examples -- Valid: const :: a -> b -> a const a _ = a -- Valid: const :: a #-> b -> a -- Not valid: const :: a -> b #-> a -- Not valid: dup :: a #-> (a, a) dup x = (x, x) 9
  • 10. Algebraic data types Most "normal" data types will have linear constructors. E.g. data Maybe a = Nothing | Just a is equivalent to data Maybe a where Nothing :: Maybe a Just :: a #-> Maybe a 10
  • 11. Unrestricted Explicitly unrestricted or non-linear constructor using GADT syntax: data Unrestricted a where Unrestricted :: a -> Unrestricted a 11
  • 12. Polymorphism Two possible types of map: map :: (a -> b) -> [a] -> [b] map :: (a #-> b) -> [a] #-> [b] — The map function preserves the multiplicity of its function argument — But we don't want to have to define it twice 12
  • 13. Polymorphism To avoid code duplication, functions can have multipicity polymorphism. map :: (a #p-> b) -> [a] #p-> [b] where p is a multiplicity parameter. — Linear functions have multiplicity or One — Unrestricted functions have multiplicity or Many 13
  • 14. Multiple multiplicities (.) :: (b #p-> c) -> (a #q-> b) -> a #(p ':* q)-> c would require 4 different types without polymorphism: (.) :: (b -> c) -> (a -> b) -> a -> c (.) :: (b #-> c) -> (a -> b) -> a -> c (.) :: (b -> c) -> (a #-> b) -> a -> c (.) :: (b #-> c) -> (a #-> b) -> a #-> c — (p ':* q) multiplies the multiplicies p and q: 14
  • 15. Details data Multiplicity = One | Many -- Type families type family (:+) (p :: Multiplicity) (q :: Multiplicity) :: Multiplicity type family (:*) (p :: Multiplicity) (q :: Multiplicity) :: Multiplicity -- New type constructor FUN :: Multiplicity -> forall (r1 r2 :: RuntimeRep). TYPE r1 -> TYPE r2 -- FUN p a b ~ a #p-> b type (->) = FUN 'Many type (#->) = FUN 'One 15
  • 17. Linear base library https://github.com/tweag/linear-base Needed to write anything useful with linear types Provides: — Linear Prelude — Linear arrays — Linear I/O — ... 17
  • 19. Trying it out — GHC 8.11 has a partial implementation of -XLinearTypes — Missing support for where and let — Missing support for multiplicity polymorphism — Probably missing other stuff too — GHC 9.0.1 will have more complete support, but still considered "experimental" — Due for release in September 2020 — linear-base library has instructions for setting up a Stack project with GHC 8.11 and linear-base using nix 19
  • 21. I/O -- Ensures I/O state is linearly threaded, meaning it is safe to -- expose the IO constructor newtype IO a = IO (State# RealWorld #-> (# State# RealWorld, a #)) -- Resource-aware IO monad (equivalent of ResourceT IO) newtype RIO a = RIO (IORef ReleaseMap -> Linear.IO a) -- Note: non-linear openFile :: FilePath -> System.IOMode -> RIO Handle -- hClose consumes the handle so it can't be used again after it's closed. hClose :: Handle #-> RIO () -- Other I/O operations must also be linear with respect to handle -- meaning each operation needs to return a new handle. hPutChar :: Handle #-> Char -> RIO Handle hGetChar :: Handle #-> RIO (Unrestricted Char, Handle) 21
  • 22. I/O linearGetFirstLine :: FilePath -> RIO (Unrestricted Text) linearGetFirstLine fp = do handle <- Linear.openFile fp System.ReadMode (t, handle') <- Linear.hGetLine handle Linear.hClose handle' return t where Control.Builder {..} = Control.monadBuilder linearPrintFirstLine :: FilePath -> System.IO () linearPrintFirstLine fp = do text <- Linear.run (linearGetFirstLine fp) System.putStrLn (unpack text) Excercise: — What happens if we forget to close the file handle? — Use the handle more than once? — Use after close? 22
  • 23. Mutable arrays fromList :: [a] -> (Array a #-> Unrestricted b) -> Unrestricted b toList :: Array a #-> (Array a, [a]) length :: Array a #-> (Array a, Int) write :: Array a #-> Int -> a -> Array a read :: Array a #-> Int -> (Array a, Unrestricted a) — Note use of continuation passing style for fromList — Required to ensure that the array is always used linearly — Operations return a "new" array Excercise: — Write a function to swap two elements in an array. 23
  • 24. void swap(int a[], int i, int j) { int t = a[i]; int u = a[j] a[i] = u; a[j] = t; } swap :: Array a #-> Int -> Int -> Array a swap a i j = Array.read a i & case (a', Unrestricted t) -> Array.read a' j & case (a'', Unrestricted u) -> Array.write a'' i u & a''' -> Array.write a''' j t 24
  • 26. — Linear Types Can Change the World!, Philip Wadler, 1990 — Based on Linear Logic — Linearity on types rather than functions — Clean — Uniqueness types - "I have the only unique reference to this object" — Used for I/O state — Mercury — Uniqueness using modes — Rust — Ownership and borrowing have similarites to uniqueness and linearity, respectively 26
  • 27. The Linearity Design Space1 Linearity on the arrows Linearity on the kinds Linear types Linear Haskell Rust (borrowing) Uniqueness types Rust (ownership), Clean, Mercury (modes) 1  Taken from SPJ's talk 27
  • 28. References — Linear Haskell - Practical Linearity in a Higher-Order Polymorphic Langauge, Bernardy et al, Nov 2017. — GHC Proposal — Linear Base Library — Examples — Simon Peyton Jones - Linear Haskell: practical linearity in a higher-order polymorphic language — Linear types can change the world! - Philip Wadler, 1990 28