SlideShare una empresa de Scribd logo
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 first, unit tests second
Thanks
Questions?
Leonardo Borges
@leonardo_borges
www.atlassian.com
www.leonardoborges.com

Más contenido relacionado

La actualidad más candente

Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
Radim Pavlicek
 
Quinto Punto Parte B
Quinto Punto Parte BQuinto Punto Parte B
Quinto Punto Parte Bgustavo206
 
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
John De Goes
 
Formalization Machines and Sastes
Formalization Machines and SastesFormalization Machines and Sastes
Formalization Machines and Sastes
Lahiru Danushka
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
John De Goes
 
Stack application
Stack applicationStack application
Stack application
Student
 
Halogen: Past, Present, and Future
Halogen: Past, Present, and FutureHalogen: Past, Present, and Future
Halogen: Past, Present, and Future
John De Goes
 
Orthogonal Functional Architecture
Orthogonal Functional ArchitectureOrthogonal Functional Architecture
Orthogonal Functional Architecture
John De Goes
 
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)
Yuriy Tymchuk
 
Newton cotes method
Newton cotes methodNewton cotes method
Newton cotes method
Faisal Saeed
 
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
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
 
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
FoCAS Initiative
 
Faisal
FaisalFaisal
Faisal
Faisal Saeed
 
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
aluavi
 
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
John De Goes
 
Scalaz
ScalazScalaz
Scalaz
mpilquist
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
John De Goes
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaz
nkpart
 

La actualidad más candente (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 a Parametricity - #cljsyd - May, 2015

Monadologie
MonadologieMonadologie
Monadologie
league
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
Hang Zhao
 
The Magnificent Seven
The Magnificent SevenThe Magnificent Seven
The Magnificent SevenMike 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
 
Functional Operations - Susan Potter
Functional Operations - Susan PotterFunctional Operations - Susan Potter
Functional Operations - Susan Potter
distributed matters
 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
Vladimir Parfinenko
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
Eduard Tomàs
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
Eta
EtaEta
Introduction To Lisp
Introduction To LispIntroduction To Lisp
Introduction To Lisp
kyleburton
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
John De Goes
 
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
Jarek Ratajski
 
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
 
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...
NaumanMalik30
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
league
 
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
Hang Zhao
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
kenbot
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programming
Alberto Labarga
 

Similar a 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
 

Más de Leonardo Borges

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
Leonardo Borges
 
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
Leonardo Borges
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library design
Leonardo Borges
 
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
Leonardo Borges
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsLeonardo Borges
 
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
Leonardo Borges
 
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
Leonardo Borges
 
Monads in Clojure
Monads in ClojureMonads in Clojure
Monads in Clojure
Leonardo Borges
 
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
Leonardo Borges
 
Intro to Clojure's core.async
Intro to Clojure's core.asyncIntro to Clojure's core.async
Intro to Clojure's core.async
Leonardo Borges
 
Functional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptFunctional Reactive Programming in Clojurescript
Functional Reactive Programming in Clojurescript
Leonardo Borges
 
Clojure/West 2013 in 30 mins
Clojure/West 2013 in 30 minsClojure/West 2013 in 30 mins
Clojure/West 2013 in 30 mins
Leonardo Borges
 
Clojure Reducers / clj-syd Aug 2012
Clojure Reducers / clj-syd Aug 2012Clojure Reducers / clj-syd Aug 2012
Clojure Reducers / clj-syd Aug 2012
Leonardo Borges
 
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
Leonardo Borges
 
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
Leonardo Borges
 
Heroku addons development - Nov 2011
Heroku addons development - Nov 2011Heroku addons development - Nov 2011
Heroku addons development - Nov 2011
Leonardo Borges
 
Clouds against the Floods (RubyConfBR2011)
Clouds against the Floods (RubyConfBR2011) Clouds against the Floods (RubyConfBR2011)
Clouds against the Floods (RubyConfBR2011) Leonardo Borges
 
Clouds Against the Floods
Clouds Against the FloodsClouds Against the Floods
Clouds Against the Floods
Leonardo Borges
 

Más de 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
 

Último

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
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
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
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
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
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
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
 
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
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
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
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
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 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
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
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
 

Último (20)

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
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
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
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
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...
 
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
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
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
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
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
 

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 first, unit tests second