SlideShare a Scribd company logo
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

More Related Content

What's hot

파이썬+함수이해하기 20160229
파이썬+함수이해하기 20160229파이썬+함수이해하기 20160229
파이썬+함수이해하기 20160229
Yong Joon Moon
 
Profundizando manager
Profundizando managerProfundizando manager
Profundizando manager
Elio Rojano
 
Anatomy of file read in hadoop
Anatomy of file read in hadoopAnatomy of file read in hadoop
Anatomy of file read in hadoop
Rajesh Ananda Kumar
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perl
deepfountainconsulting
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in Java
CODE WHITE GmbH
 
Лекция 3: Бинарный поиск. Связные списки
Лекция 3: Бинарный поиск. Связные спискиЛекция 3: Бинарный поиск. Связные списки
Лекция 3: Бинарный поиск. Связные спискиMikhail Kurnosov
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
Scott Wlaschin
 
Numpy python cheat_sheet
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheet
Zahid Hasan
 
TCPdump-Wireshark
TCPdump-WiresharkTCPdump-Wireshark
TCPdump-WiresharkHarsh Singh
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
Syed Zaid Irshad
 
Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013
Scott Wlaschin
 
Cours pointeurs
Cours pointeursCours pointeurs
Cours pointeurs
Brahim BESSAA
 
Comonads in Haskell
Comonads in HaskellComonads in Haskell
Comonads in Haskell
David Overton
 
Введение в программирование (1 часть)
Введение в программирование (1 часть)Введение в программирование (1 часть)
Введение в программирование (1 часть)
Timur Shemsedinov
 
Celery with python
Celery with pythonCelery with python
Celery with python
Alexandre González Rodríguez
 
The Power Of Composition (DotNext 2019)
The Power Of Composition (DotNext 2019)The Power Of Composition (DotNext 2019)
The Power Of Composition (DotNext 2019)
Scott Wlaschin
 
Serverless Clouds (FaaS) and request context isolation in Node.js
Serverless Clouds (FaaS) and request context isolation in Node.jsServerless Clouds (FaaS) and request context isolation in Node.js
Serverless Clouds (FaaS) and request context isolation in Node.js
Timur Shemsedinov
 
網頁安全 Web security 入門 @ Study-Area
網頁安全 Web security 入門 @ Study-Area網頁安全 Web security 入門 @ Study-Area
網頁安全 Web security 入門 @ Study-Area
Orange Tsai
 
UserParameter vs Zabbix Sender - 1º ZABBIX MEETUP DO INTERIOR-SP
UserParameter vs Zabbix Sender - 1º ZABBIX MEETUP DO INTERIOR-SPUserParameter vs Zabbix Sender - 1º ZABBIX MEETUP DO INTERIOR-SP
UserParameter vs Zabbix Sender - 1º ZABBIX MEETUP DO INTERIOR-SP
André Déo
 

What's hot (20)

파이썬+함수이해하기 20160229
파이썬+함수이해하기 20160229파이썬+함수이해하기 20160229
파이썬+함수이해하기 20160229
 
Profundizando manager
Profundizando managerProfundizando manager
Profundizando manager
 
Anatomy of file read in hadoop
Anatomy of file read in hadoopAnatomy of file read in hadoop
Anatomy of file read in hadoop
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perl
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in Java
 
Лекция 3: Бинарный поиск. Связные списки
Лекция 3: Бинарный поиск. Связные спискиЛекция 3: Бинарный поиск. Связные списки
Лекция 3: Бинарный поиск. Связные списки
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
 
Numpy python cheat_sheet
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheet
 
TCPdump-Wireshark
TCPdump-WiresharkTCPdump-Wireshark
TCPdump-Wireshark
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 
Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013
 
Cours pointeurs
Cours pointeursCours pointeurs
Cours pointeurs
 
Comonads in Haskell
Comonads in HaskellComonads in Haskell
Comonads in Haskell
 
Введение в программирование (1 часть)
Введение в программирование (1 часть)Введение в программирование (1 часть)
Введение в программирование (1 часть)
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
The Power Of Composition (DotNext 2019)
The Power Of Composition (DotNext 2019)The Power Of Composition (DotNext 2019)
The Power Of Composition (DotNext 2019)
 
Serverless Clouds (FaaS) and request context isolation in Node.js
Serverless Clouds (FaaS) and request context isolation in Node.jsServerless Clouds (FaaS) and request context isolation in Node.js
Serverless Clouds (FaaS) and request context isolation in Node.js
 
網頁安全 Web security 入門 @ Study-Area
網頁安全 Web security 入門 @ Study-Area網頁安全 Web security 入門 @ Study-Area
網頁安全 Web security 入門 @ Study-Area
 
Cours php
Cours phpCours php
Cours php
 
UserParameter vs Zabbix Sender - 1º ZABBIX MEETUP DO INTERIOR-SP
UserParameter vs Zabbix Sender - 1º ZABBIX MEETUP DO INTERIOR-SPUserParameter vs Zabbix Sender - 1º ZABBIX MEETUP DO INTERIOR-SP
UserParameter vs Zabbix Sender - 1º ZABBIX MEETUP DO INTERIOR-SP
 

Similar to Linear Types in Haskell

Java 8
Java 8Java 8
Java 8
vilniusjug
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
Manav Prasad
 
C standard library functions
C standard library functionsC standard library functions
C standard library functions
Vaishnavee 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-answers
Akash Gawali
 
Overview of Chainer and Its Features
Overview of Chainer and Its FeaturesOverview of Chainer and Its Features
Overview of Chainer and Its Features
Seiya Tokui
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
Shimi Bandiel
 
あなたの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 spark
Angelo Leto
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
IndicThreads
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
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
Sergii 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 framework
Felipe
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus 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 Odersky
Typesafe
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packagesAjay Ohri
 
Java8
Java8Java8
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric 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 - JavaTpoint
JavaTpoint.Com
 

Similar to 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 Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and 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
 

Recently uploaded

SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
kalichargn70th171
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 

Recently uploaded (20)

SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 

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