SlideShare a Scribd company logo
1 of 42
Download to read offline
Parametricity
or why types are useful
#cljsyd - May, 2015
Leonardo Borges
@leonardo_borges
www.atlassian.com
www.leonardoborges.com
Hereā€™s the plan
ā€£ Parametricity and Fast and loose reasoning
ā€£ Breaking parametricity
ā€£ Property-based tests
(ann irrelevant (All [x] [(Seq x) -> (Seq x)]))
(defn irrelevant [xs]
xs)
Theorem
Every element A in the result sequence appears in the input.
(ann irrelevant (All [x] [(Seq x) -> (Seq x)]))
(defn irrelevant [xs]
xs)
(ann irrelevant (All [a b] [a -> b]))
(defn irrelevant [a]
(irrelevant a))
Theorem
This function never returns because if it did, it would never have compiled
(ann irrelevant (All [a b] [a -> b]))
(defn irrelevant [a]
(irrelevant a))
(ann even? [Number -> Boolean])
(defn even? [p]
(= (mod p 2) 0))
Theorem
The even function returns either true or false
(ann even? [Number -> Boolean])
(defn even? [p]
(= (mod p 2) 0))
Escape hatches
ā€£ null (actually not an issue in core.typed)
ā€£ exceptions
ā€£ Type-casing (isInstanceOf)
ā€£ Type-casting (asInstanceOf)
ā€£ Side-effects
ā€£ equals/toString/hashCode
ā€£ notify/wait
ā€£ classOf/.getClass
ā€£ General recursion
Escape hatches
ā€£ null (actually not an issue in core.typed)
ā€£ exceptions
ā€£ Type-casing (isInstanceOf)
ā€£ Type-casting (asInstanceOf)
ā€£ Side-effects
ā€£ equals/toString/hashCode
ā€£ notify/wait
ā€£ classOf/.getClass
ā€£ General recursion
Theorem
Every element A in the result sequence appears in the input.
(ann irrelevant (All [x] [(Seq x) -> (Seq x)]))
(defn irrelevant [xs]
nil)
Theorem
Every element A in the result sequence appears in the input.
(ann irrelevant (All [x] [(Seq x) -> (Seq x)]))
(defn irrelevant [xs]
nil)
Doesnā€™t compile with core.typed!
Theorem
This function ignores its argument and consistently returns either true or false
(ann irrelevant (All [a] [a -> Boolean]))
(defn irrelevant [a]
(or (instance? Long 1)
(and (instance? String a)
(< (count a) 10))))
Theorem
This function ignores its argument and consistently returns either true or false
(ann irrelevant (All [a] [a -> Boolean]))
(defn irrelevant [a]
(or (instance? Long 1)
(and (instance? String a)
(< (count a) 10))))
Theorem
Every A element in the result list appears in the input list
(ann irrelevant (All [x] [(Seq x) -> (Seq x)]))
(defn irrelevant [xs]
(cons (cast "abc" 'x) xs))
Theorem
Every A element in the result list appears in the input list
(ann irrelevant (All [x] [(Seq x) -> (Seq x)]))
(defn irrelevant [xs]
(cons (cast "abc" 'x) xs))
Doesnā€™t compile with core.typed!
Theorem
This function only ever does one thing ā€”return its argument
(ann irrelevant (All [a] [a -> a]))
(defn irrelevant [x]
(prn "hi")
x)
Theorem
This function only ever does one thing ā€”return its argument
(ann irrelevant (All [a] [a -> a]))
(defn irrelevant [x]
(prn "hi")
x)
Theorem
This function ignores its argument to return one of 2^32 values.
(ann irrelevant (All [a] [a -> Int]))
(defn irrelevant [x]
(-> x
str
(.length)))
Theorem
This function ignores its argument to return one of 2^32 values.
(ann irrelevant (All [a] [a -> Int]))
(defn irrelevant [x]
(-> x
str
(.length)))
Theorem
This function always returns Nil and so cannot possibly reverse the list
(ann reverse (All [a b] [(Seq a) -> (Seq b)]))
(defn reverse [as]
(reduce (fn [acc a]
(conj acc (cast b a))) nil as))
Theorem
This function always returns Nil and so cannot possibly reverse the list
(ann reverse (All [a b] [(Seq a) -> (Seq b)]))
(defn reverse [as]
(reduce (fn [acc a]
(conj acc (cast b a))) nil as))
Doesnā€™t compile with core.typed!
Escape hatches
ā€£ null (actually not an issue in core.typed)
ā€£ exceptions
ā€£ Type-casing (isInstanceOf)
ā€£ Type-casting (asInstanceOf)
ā€£ Side-effects
ā€£ equals/toString/hashCode
ā€£ notify/wait
ā€£ classOf/.getClass
ā€£ General recursion
[2] http://www.cse.chalmers.se/~nad/publications/danielsson-et-al-popl2006.pdf
[1] http://ttic.uchicago.edu/~dreyer/course/papers/wadler.pdf
Where does this thinking come from?
ā€£ Theorems for Free, Philip Wadler [1]
ā€£ Fast and Loose reasoning is Morally correct, John Hughes et al. [2]
Where does this thinking come from?
What about docstrings?
Example: repeat
(defn repeat
"Returns a lazy (infinite!, or length n if supplied) sequence of xs."
([x] (clojure.lang.Repeat/create x))
([n x] (clojure.lang.Repeat/create n x)))
Example: repeat
(defn repeat
"Returns a lazy (infinite!, or length n if supplied) sequence of xs."
([x] (clojure.lang.Repeat/create x))
([n x] (clojure.lang.Repeat/create n x)))
Example: repeat
(ann repeat (All [x]
(IFn [x -> (ASeq x)]
[AnyInteger x -> (ASeq x)])))
(defn repeat
"Returns a lazy (infinite!, or length n if supplied) sequence of xs."
([x] (clojure.lang.Repeat/create x))
([n x] (clojure.lang.Repeat/create n x)))
Example: iterate
(ann iterate (All [x]
[[x -> x] x -> (ASeq x)]))
(defn iterate
"Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of
side-effects"
[f x] (clojure.lang.Iterate/create f x) )
Example: iterate
(ann iterate (All [x]
[[x -> x] x -> (ASeq x)]))
(defn iterate
"Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of
side-effects"
[f x] (clojure.lang.Iterate/create f x) )
Example: iterate
(ann iterate (All [x]
[[x -> x] x -> (ASeq x)]))
(defn iterate
"Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of
side-effects"
[f x] (clojure.lang.Iterate/create f x) )
Some other core.typed niceties
(ann underage? [(HMap :mandatory {:name String
:age Num}) -> Boolean])
(defn underage? [p]
(< (:age p) 18))
Some other core.typed niceties
(t/defalias Person (HMap :mandatory {:name String
:age Num}))
(ann underage? [Person -> Boolean])
(defn underage? [p]
(< (:age p) 18))
Some other core.typed niceties
(underage? {:age 32})
Type error:
Domains:
Person
Arguments:
(t/HMap :mandatory {:age (t/Val 17)} :complete? true)
Ranges:
java.lang.Boolean
Some other core.typed niceties
(underage? {:name "Leo" :age 32})
So types can check everything, right?
So types can check everything, right?
nope
Property based testing
(ann does-not-reverse (All [a] [(Seq a) -> (Seq a)]))
(defn does-not-reverse [xs]
...)
Property based testing
(def does-not-reverse-prop-1
(prop/for-all [x (gen/vector gen/simple-type)]
(= (does-not-reverse (does-not-reverse x))
x)))
(def does-not-reverse-prop-2
(prop/for-all [x (gen/vector gen/simple-type)
y (gen/vector gen/simple-type)]
(= (does-not-reverse (concat x y))
(concat (does-not-reverse x)
(does-not-reverse y)))))
Takeaway points
ā€£ Donā€™t dismiss types too quickly. They can improve code comprehension
and quality
ā€£ Even comments expressed in terms of types can be a big help when
reading foreign code
ā€£ Write property-based tests ļ¬rst, unit tests second
Thanks
Questions?
Leonardo Borges
@leonardo_borges
www.atlassian.com
www.leonardoborges.com

More Related Content

What's hot

Quinto Punto Parte B
Quinto Punto Parte BQuinto Punto Parte B
Quinto Punto Parte B
gustavo206
Ā 
Orthogonal Functional Architecture
Orthogonal Functional ArchitectureOrthogonal Functional Architecture
Orthogonal Functional Architecture
John De Goes
Ā 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final Tagless
John De Goes
Ā 

What's hot (20)

Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
Ā 
Quinto Punto Parte B
Quinto Punto Parte BQuinto Punto Parte B
Quinto Punto Parte B
Ā 
Blazing Fast, Pure Effects without Monads ā€” LambdaConf 2018
Blazing Fast, Pure Effects without Monads ā€” LambdaConf 2018Blazing Fast, Pure Effects without Monads ā€” LambdaConf 2018
Blazing Fast, Pure Effects without Monads ā€” LambdaConf 2018
Ā 
Formalization Machines and Sastes
Formalization Machines and SastesFormalization Machines and Sastes
Formalization Machines and Sastes
Ā 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
Ā 
Stack application
Stack applicationStack application
Stack application
Ā 
Cd
CdCd
Cd
Ā 
Halogen: Past, Present, and Future
Halogen: Past, Present, and FutureHalogen: Past, Present, and Future
Halogen: Past, Present, and Future
Ā 
Orthogonal Functional Architecture
Orthogonal Functional ArchitectureOrthogonal Functional Architecture
Orthogonal Functional Architecture
Ā 
The False False Positives of Static Analysis (sattose2017)
The False False Positives of Static Analysis (sattose2017)The False False Positives of Static Analysis (sattose2017)
The False False Positives of Static Analysis (sattose2017)
Ā 
Newton cotes method
Newton cotes methodNewton cotes method
Newton cotes method
Ā 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect System
Ā 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final Tagless
Ā 
Artificial software diversity: automatic synthesis of program sosies
Artificial software diversity: automatic synthesis of program sosiesArtificial software diversity: automatic synthesis of program sosies
Artificial software diversity: automatic synthesis of program sosies
Ā 
Faisal
FaisalFaisal
Faisal
Ā 
Write a program to check a given number is prime or not
Write a program to check a given number is prime or notWrite a program to check a given number is prime or not
Write a program to check a given number is prime or not
Ā 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Ā 
Scalaz
ScalazScalaz
Scalaz
Ā 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
Ā 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaz
Ā 

Similar to Parametricity - #cljsyd - May, 2015

The Magnificent Seven
The Magnificent SevenThe Magnificent Seven
The Magnificent Seven
Mike Fogus
Ā 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
Ā 
Š”тŠ¾Š»Šæы фуŠ½ŠŗцŠøŠ¾Š½Š°Š»ŃŒŠ½Š¾Š³Š¾ ŠæрŠ¾Š³Ń€Š°Š¼Š¼ŠøрŠ¾Š²Š°Š½Šøя Š“Š»Ń Š°Š“ŠµŠæтŠ¾Š² ŠžŠžŠŸ, ŠŠøŠŗŠ¾Š»Š°Š¹ ŠœŠ¾Š·Š³Š¾Š²Š¾Š¹
Š”тŠ¾Š»Šæы фуŠ½ŠŗцŠøŠ¾Š½Š°Š»ŃŒŠ½Š¾Š³Š¾ ŠæрŠ¾Š³Ń€Š°Š¼Š¼ŠøрŠ¾Š²Š°Š½Šøя Š“Š»Ń Š°Š“ŠµŠæтŠ¾Š² ŠžŠžŠŸ, ŠŠøŠŗŠ¾Š»Š°Š¹ ŠœŠ¾Š·Š³Š¾Š²Š¾Š¹Š”тŠ¾Š»Šæы фуŠ½ŠŗцŠøŠ¾Š½Š°Š»ŃŒŠ½Š¾Š³Š¾ ŠæрŠ¾Š³Ń€Š°Š¼Š¼ŠøрŠ¾Š²Š°Š½Šøя Š“Š»Ń Š°Š“ŠµŠæтŠ¾Š² ŠžŠžŠŸ, ŠŠøŠŗŠ¾Š»Š°Š¹ ŠœŠ¾Š·Š³Š¾Š²Š¾Š¹
Š”тŠ¾Š»Šæы фуŠ½ŠŗцŠøŠ¾Š½Š°Š»ŃŒŠ½Š¾Š³Š¾ ŠæрŠ¾Š³Ń€Š°Š¼Š¼ŠøрŠ¾Š²Š°Š½Šøя Š“Š»Ń Š°Š“ŠµŠæтŠ¾Š² ŠžŠžŠŸ, ŠŠøŠŗŠ¾Š»Š°Š¹ ŠœŠ¾Š·Š³Š¾Š²Š¾Š¹
Sigma Software
Ā 
yield and return (poor English ver)
yield and return (poor English ver)yield and return (poor English ver)
yield and return (poor English ver)
bleis tift
Ā 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
Vincent Pradeilles
Ā 

Similar to Parametricity - #cljsyd - May, 2015 (20)

Monadologie
MonadologieMonadologie
Monadologie
Ā 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Ā 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
Ā 
The Magnificent Seven
The Magnificent SevenThe Magnificent Seven
The Magnificent Seven
Ā 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Ā 
Functional Operations - Susan Potter
Functional Operations - Susan PotterFunctional Operations - Susan Potter
Functional Operations - Susan Potter
Ā 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
Ā 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
Ā 
Š”тŠ¾Š»Šæы фуŠ½ŠŗцŠøŠ¾Š½Š°Š»ŃŒŠ½Š¾Š³Š¾ ŠæрŠ¾Š³Ń€Š°Š¼Š¼ŠøрŠ¾Š²Š°Š½Šøя Š“Š»Ń Š°Š“ŠµŠæтŠ¾Š² ŠžŠžŠŸ, ŠŠøŠŗŠ¾Š»Š°Š¹ ŠœŠ¾Š·Š³Š¾Š²Š¾Š¹
Š”тŠ¾Š»Šæы фуŠ½ŠŗцŠøŠ¾Š½Š°Š»ŃŒŠ½Š¾Š³Š¾ ŠæрŠ¾Š³Ń€Š°Š¼Š¼ŠøрŠ¾Š²Š°Š½Šøя Š“Š»Ń Š°Š“ŠµŠæтŠ¾Š² ŠžŠžŠŸ, ŠŠøŠŗŠ¾Š»Š°Š¹ ŠœŠ¾Š·Š³Š¾Š²Š¾Š¹Š”тŠ¾Š»Šæы фуŠ½ŠŗцŠøŠ¾Š½Š°Š»ŃŒŠ½Š¾Š³Š¾ ŠæрŠ¾Š³Ń€Š°Š¼Š¼ŠøрŠ¾Š²Š°Š½Šøя Š“Š»Ń Š°Š“ŠµŠæтŠ¾Š² ŠžŠžŠŸ, ŠŠøŠŗŠ¾Š»Š°Š¹ ŠœŠ¾Š·Š³Š¾Š²Š¾Š¹
Š”тŠ¾Š»Šæы фуŠ½ŠŗцŠøŠ¾Š½Š°Š»ŃŒŠ½Š¾Š³Š¾ ŠæрŠ¾Š³Ń€Š°Š¼Š¼ŠøрŠ¾Š²Š°Š½Šøя Š“Š»Ń Š°Š“ŠµŠæтŠ¾Š² ŠžŠžŠŸ, ŠŠøŠŗŠ¾Š»Š°Š¹ ŠœŠ¾Š·Š³Š¾Š²Š¾Š¹
Ā 
Eta
EtaEta
Eta
Ā 
Introduction To Lisp
Introduction To LispIntroduction To Lisp
Introduction To Lisp
Ā 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
Ā 
Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVM
Ā 
yield and return (poor English ver)
yield and return (poor English ver)yield and return (poor English ver)
yield and return (poor English ver)
Ā 
An introduction to property-based testing
An introduction to property-based testingAn introduction to property-based testing
An introduction to property-based testing
Ā 
Clips basics how to make expert system in clips | facts adding | rules makin...
Clips basics  how to make expert system in clips | facts adding | rules makin...Clips basics  how to make expert system in clips | facts adding | rules makin...
Clips basics how to make expert system in clips | facts adding | rules makin...
Ā 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
Ā 
Fp in scala with adts part 2
Fp in scala with adts part 2Fp in scala with adts part 2
Fp in scala with adts part 2
Ā 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
Ā 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programming
Ā 

More from Leonardo Borges

Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
Ā 
Clouds against the Floods (RubyConfBR2011)
Clouds against the Floods (RubyConfBR2011) Clouds against the Floods (RubyConfBR2011)
Clouds against the Floods (RubyConfBR2011)
Leonardo Borges
Ā 
Testing with Spring
Testing with SpringTesting with Spring
Testing with Spring
Leonardo Borges
Ā 

More from Leonardo Borges (20)

Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015
Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015
Realtime collaboration with Clojure - EuroClojure - Barcelona, 2015
Ā 
From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019
Ā 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library design
Ā 
Futures e abstraĆ§Ć£o - QCon SĆ£o Paulo 2015
Futures e abstraĆ§Ć£o - QCon SĆ£o Paulo 2015Futures e abstraĆ§Ć£o - QCon SĆ£o Paulo 2015
Futures e abstraĆ§Ć£o - QCon SĆ£o Paulo 2015
Ā 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
Ā 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScript
Ā 
ProgramaĆ§Ć£o functional reativa: lidando com cĆ³digo assĆ­ncrono
ProgramaĆ§Ć£o functional reativa: lidando com cĆ³digo assĆ­ncronoProgramaĆ§Ć£o functional reativa: lidando com cĆ³digo assĆ­ncrono
ProgramaĆ§Ć£o functional reativa: lidando com cĆ³digo assĆ­ncrono
Ā 
Monads in Clojure
Monads in ClojureMonads in Clojure
Monads in Clojure
Ā 
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013
Clojure Macros Workshop: LambdaJam 2013 / CUFP 2013
Ā 
Intro to Clojure's core.async
Intro to Clojure's core.asyncIntro to Clojure's core.async
Intro to Clojure's core.async
Ā 
Functional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptFunctional Reactive Programming in Clojurescript
Functional Reactive Programming in Clojurescript
Ā 
Clojure/West 2013 in 30 mins
Clojure/West 2013 in 30 minsClojure/West 2013 in 30 mins
Clojure/West 2013 in 30 mins
Ā 
Clojure Reducers / clj-syd Aug 2012
Clojure Reducers / clj-syd Aug 2012Clojure Reducers / clj-syd Aug 2012
Clojure Reducers / clj-syd Aug 2012
Ā 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
Ā 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012
Ā 
Heroku addons development - Nov 2011
Heroku addons development - Nov 2011Heroku addons development - Nov 2011
Heroku addons development - Nov 2011
Ā 
Clouds against the Floods (RubyConfBR2011)
Clouds against the Floods (RubyConfBR2011) Clouds against the Floods (RubyConfBR2011)
Clouds against the Floods (RubyConfBR2011)
Ā 
Clouds Against the Floods
Clouds Against the FloodsClouds Against the Floods
Clouds Against the Floods
Ā 
Arel in Rails 3
Arel in Rails 3Arel in Rails 3
Arel in Rails 3
Ā 
Testing with Spring
Testing with SpringTesting with Spring
Testing with Spring
Ā 

Recently uploaded

Abortion Pills In Pretoria ](+27832195400*)[ šŸ„ Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ šŸ„ Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ šŸ„ Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ šŸ„ Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
Ā 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
Ā 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
Ā 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
Ā 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
Ā 
Abortion Pill Prices Tembisa [(+27832195400*)] šŸ„ Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] šŸ„ Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] šŸ„ Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] šŸ„ Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
Ā 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
Ā 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
Ā 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
Ā 

Recently uploaded (20)

WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
Ā 
Abortion Pills In Pretoria ](+27832195400*)[ šŸ„ Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ šŸ„ Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ šŸ„ Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ šŸ„ Women's Abortion Clinic In Pre...
Ā 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
Ā 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
Ā 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
Ā 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
Ā 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
Ā 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
Ā 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
Ā 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
Ā 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
Ā 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Ā 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
Ā 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
Ā 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Ā 
Abortion Pill Prices Tembisa [(+27832195400*)] šŸ„ Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] šŸ„ Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] šŸ„ Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] šŸ„ Women's Abortion Clinic in T...
Ā 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
Ā 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
Ā 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
Ā 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Ā 

Parametricity - #cljsyd - May, 2015

  • 1. Parametricity or why types are useful #cljsyd - May, 2015 Leonardo Borges @leonardo_borges www.atlassian.com www.leonardoborges.com
  • 2. Hereā€™s the plan ā€£ Parametricity and Fast and loose reasoning ā€£ Breaking parametricity ā€£ Property-based tests
  • 3. (ann irrelevant (All [x] [(Seq x) -> (Seq x)])) (defn irrelevant [xs] xs)
  • 4. Theorem Every element A in the result sequence appears in the input. (ann irrelevant (All [x] [(Seq x) -> (Seq x)])) (defn irrelevant [xs] xs)
  • 5. (ann irrelevant (All [a b] [a -> b])) (defn irrelevant [a] (irrelevant a))
  • 6. Theorem This function never returns because if it did, it would never have compiled (ann irrelevant (All [a b] [a -> b])) (defn irrelevant [a] (irrelevant a))
  • 7. (ann even? [Number -> Boolean]) (defn even? [p] (= (mod p 2) 0))
  • 8. Theorem The even function returns either true or false (ann even? [Number -> Boolean]) (defn even? [p] (= (mod p 2) 0))
  • 9. Escape hatches ā€£ null (actually not an issue in core.typed) ā€£ exceptions ā€£ Type-casing (isInstanceOf) ā€£ Type-casting (asInstanceOf) ā€£ Side-effects ā€£ equals/toString/hashCode ā€£ notify/wait ā€£ classOf/.getClass ā€£ General recursion
  • 10. Escape hatches ā€£ null (actually not an issue in core.typed) ā€£ exceptions ā€£ Type-casing (isInstanceOf) ā€£ Type-casting (asInstanceOf) ā€£ Side-effects ā€£ equals/toString/hashCode ā€£ notify/wait ā€£ classOf/.getClass ā€£ General recursion
  • 11. Theorem Every element A in the result sequence appears in the input. (ann irrelevant (All [x] [(Seq x) -> (Seq x)])) (defn irrelevant [xs] nil)
  • 12. Theorem Every element A in the result sequence appears in the input. (ann irrelevant (All [x] [(Seq x) -> (Seq x)])) (defn irrelevant [xs] nil) Doesnā€™t compile with core.typed!
  • 13. Theorem This function ignores its argument and consistently returns either true or false (ann irrelevant (All [a] [a -> Boolean])) (defn irrelevant [a] (or (instance? Long 1) (and (instance? String a) (< (count a) 10))))
  • 14. Theorem This function ignores its argument and consistently returns either true or false (ann irrelevant (All [a] [a -> Boolean])) (defn irrelevant [a] (or (instance? Long 1) (and (instance? String a) (< (count a) 10))))
  • 15. Theorem Every A element in the result list appears in the input list (ann irrelevant (All [x] [(Seq x) -> (Seq x)])) (defn irrelevant [xs] (cons (cast "abc" 'x) xs))
  • 16. Theorem Every A element in the result list appears in the input list (ann irrelevant (All [x] [(Seq x) -> (Seq x)])) (defn irrelevant [xs] (cons (cast "abc" 'x) xs)) Doesnā€™t compile with core.typed!
  • 17. Theorem This function only ever does one thing ā€”return its argument (ann irrelevant (All [a] [a -> a])) (defn irrelevant [x] (prn "hi") x)
  • 18. Theorem This function only ever does one thing ā€”return its argument (ann irrelevant (All [a] [a -> a])) (defn irrelevant [x] (prn "hi") x)
  • 19. Theorem This function ignores its argument to return one of 2^32 values. (ann irrelevant (All [a] [a -> Int])) (defn irrelevant [x] (-> x str (.length)))
  • 20. Theorem This function ignores its argument to return one of 2^32 values. (ann irrelevant (All [a] [a -> Int])) (defn irrelevant [x] (-> x str (.length)))
  • 21. Theorem This function always returns Nil and so cannot possibly reverse the list (ann reverse (All [a b] [(Seq a) -> (Seq b)])) (defn reverse [as] (reduce (fn [acc a] (conj acc (cast b a))) nil as))
  • 22. Theorem This function always returns Nil and so cannot possibly reverse the list (ann reverse (All [a b] [(Seq a) -> (Seq b)])) (defn reverse [as] (reduce (fn [acc a] (conj acc (cast b a))) nil as)) Doesnā€™t compile with core.typed!
  • 23. Escape hatches ā€£ null (actually not an issue in core.typed) ā€£ exceptions ā€£ Type-casing (isInstanceOf) ā€£ Type-casting (asInstanceOf) ā€£ Side-effects ā€£ equals/toString/hashCode ā€£ notify/wait ā€£ classOf/.getClass ā€£ General recursion
  • 24. [2] http://www.cse.chalmers.se/~nad/publications/danielsson-et-al-popl2006.pdf [1] http://ttic.uchicago.edu/~dreyer/course/papers/wadler.pdf Where does this thinking come from? ā€£ Theorems for Free, Philip Wadler [1] ā€£ Fast and Loose reasoning is Morally correct, John Hughes et al. [2]
  • 25. Where does this thinking come from?
  • 27. Example: repeat (defn repeat "Returns a lazy (infinite!, or length n if supplied) sequence of xs." ([x] (clojure.lang.Repeat/create x)) ([n x] (clojure.lang.Repeat/create n x)))
  • 28. Example: repeat (defn repeat "Returns a lazy (infinite!, or length n if supplied) sequence of xs." ([x] (clojure.lang.Repeat/create x)) ([n x] (clojure.lang.Repeat/create n x)))
  • 29. Example: repeat (ann repeat (All [x] (IFn [x -> (ASeq x)] [AnyInteger x -> (ASeq x)]))) (defn repeat "Returns a lazy (infinite!, or length n if supplied) sequence of xs." ([x] (clojure.lang.Repeat/create x)) ([n x] (clojure.lang.Repeat/create n x)))
  • 30. Example: iterate (ann iterate (All [x] [[x -> x] x -> (ASeq x)])) (defn iterate "Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of side-effects" [f x] (clojure.lang.Iterate/create f x) )
  • 31. Example: iterate (ann iterate (All [x] [[x -> x] x -> (ASeq x)])) (defn iterate "Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of side-effects" [f x] (clojure.lang.Iterate/create f x) )
  • 32. Example: iterate (ann iterate (All [x] [[x -> x] x -> (ASeq x)])) (defn iterate "Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of side-effects" [f x] (clojure.lang.Iterate/create f x) )
  • 33. Some other core.typed niceties (ann underage? [(HMap :mandatory {:name String :age Num}) -> Boolean]) (defn underage? [p] (< (:age p) 18))
  • 34. Some other core.typed niceties (t/defalias Person (HMap :mandatory {:name String :age Num})) (ann underage? [Person -> Boolean]) (defn underage? [p] (< (:age p) 18))
  • 35. Some other core.typed niceties (underage? {:age 32}) Type error: Domains: Person Arguments: (t/HMap :mandatory {:age (t/Val 17)} :complete? true) Ranges: java.lang.Boolean
  • 36. Some other core.typed niceties (underage? {:name "Leo" :age 32})
  • 37. So types can check everything, right?
  • 38. So types can check everything, right? nope
  • 39. Property based testing (ann does-not-reverse (All [a] [(Seq a) -> (Seq a)])) (defn does-not-reverse [xs] ...)
  • 40. Property based testing (def does-not-reverse-prop-1 (prop/for-all [x (gen/vector gen/simple-type)] (= (does-not-reverse (does-not-reverse x)) x))) (def does-not-reverse-prop-2 (prop/for-all [x (gen/vector gen/simple-type) y (gen/vector gen/simple-type)] (= (does-not-reverse (concat x y)) (concat (does-not-reverse x) (does-not-reverse y)))))
  • 41. Takeaway points ā€£ Donā€™t dismiss types too quickly. They can improve code comprehension and quality ā€£ Even comments expressed in terms of types can be a big help when reading foreign code ā€£ Write property-based tests ļ¬rst, unit tests second