SlideShare a Scribd company logo
Simon Peyton Jones (Microsoft Research)
              Chung-Chieh Shan (Rutgers University)
Oleg Kiselyov (Fleet Numerical Meteorology and Oceanography Center)


 Tony Hoare’s 75th birthday celebration, April 2009
 “Program correctness is a basic scientific ideal
      for Computer Science”
     “The most widely used tools [in pursuit of
      correctness] concentrate on the detection of
      programming errors, widely known as bugs.
      Foremost among these [tools] are modern
      compilers for strongly typed languages”
     “Like insects that carry disease, the least
      efficient way of eradicating program bugs is by
      squashing them one by one. The only sure
      safeguard against attack is to pursue the ideal
      of not making the errors in the first place.”
“The ideal of program correctness”, Tony Hoare, BCS lecture and debate, Oct 2006
 Static typing eradicates whole species of bugs
 The static type of a function is a partial
  specification: its says something (but not too
  much) about what the function does
     reverse :: [a] -> [a]
      Increasingly precise specification
       The spectrum of confidence
              Increasing
          confidence that the
          program does what
               you want
 The static type of a function is like a weak
  specification: its says something (but not too
  much) about what the function does
     reverse :: [a] -> [a]
 Static typing is by far the most widely-used
  program verification technology in use today:
  particularly good cost/benefit ratio
   Lightweight (so programmers use them)
   Machine checked (fully automated, every compilation)
   Ubiquitous (so programmers can’t avoid them)
 Static typing eradicates whole species of bugs
    Static typing is by far the most widely-used
     program verification technology in use today:
     particularly good cost/benefit ratio


                Increasingly precise specification
                The spectrum of confidence
  Hammer                Increasing
(cheap, easy        confidence that the       Tactical nuclear weapon
    to use,                                  (expensive, needs a trained
                    program does what
   limited                                     user, but very effective
effectivenes)            you want                      indeed)
 The type system designer seeks to
 Retain the Joyful Properties of types
 While also:
   making more good programs pass the type
    checker
   making fewer bad programs pass the type
    checker
Programs that   All programs
    work
                  Programs that are
                      well typed




Make this bit
  bigger!
 The type system designer seeks to retain
  the Joyful Properties of types
 While also:
   making more good programs pass the type
    checker
   making fewer bad programs pass the type
    checker

 One such endeavour:
            Extend Haskell with
           Indexed type families
 The type system designer seeks to retain
  the Joyful Properties of types
                                 I fear that
 While also:                     Haskell is
                                 doomed to
   making more good programs pass the type
    checker                        succeed
   making fewer bad programs pass the type
    checker

 One such endeavour:                         Tony
                                              Hoare
            Extend Haskell with               (1990)

           Indexed type families
Class decl gives type
   signature of each
         method

                               class Num a where
                                 (+), (*) :: a -> a -> a
                                 negate   :: a -> a

 Instance decl gives a         square :: Num a => a -> a
  “witness” for each
                               square x = x*x
 method, matching the
      signature
                               instance   Num Int where
                                 (+)      = plusInt
                                 (*)      = mulInt
                                 negate   = negInt
plusInt :: Int -> Int -> Int
mulInt :: Int -> Int -> Int
negInt :: Int -> Int           test = square 4 + 5 :: Int
plusInt    :: Int -> Int -> Int
                    plusFloat :: Float -> Float -> Float
                    intToFloat :: Int -> Float




class GNum a b where
  (+) :: a -> b -> ???

instance GNum Int Int where
  (+) x y = plusInt x y

instance GNum Int Float where
  (+) x y = plusFloat (intToFloat x) y

test1 = (4::Int) + (5::Int)
test2 = (4::Int) + (5::Float)

                              Allowing more good
                                   programs
class GNum a b where
     (+) :: a -> b -> ???

 Result type of (+) is a function of the
  argument types                      SumTy is an
                                     associated type of
   class GNum a b where                 class GNum
     type SumTy a b :: *
     (+) :: a -> b -> SumTy a b

 Each method gets a type signature
 Each associated type gets a kind signature
class GNum a b where
    type SumTy a b :: *
    (+) :: a -> b -> SumTy a b
 Each instance declaration gives a “witness”
  for SumTy, matching the kind signature
  instance GNum Int Int where
    type SumTy Int Int = Int
    (+) x y = plusInt x y

  instance GNum Int Float where
    type SumTy Int Float = Float
    (+) x y = plusFloat (intToFloat x) y
class GNum a b where
    type SumTy a b :: *
  instance GNum Int Int where
    type SumTy Int Int = Int :: *
  instance GNum Int Float where
    type SumTy Int Float = Float

 SumTy is a type-level function
 The type checker simply rewrites
   SumTy Int Int --> Int
   SumTy Int Float --> Float
  whenever it can

 But (SumTy t1 t2) is still a perfectly good type,
  even if it can’t be rewritten. For example:
   data T a b = MkT a b (SumTy a b)
 Simply omit instances for incompatible types
  newtype Dollars = MkD Int

  instance GNum Dollars Dollars where
    type SumTy Dollars Dollars = Dollars
    (+) (MkD d1) (MkD d2) = MkD (d1+d2)

  -- No instance GNum Dollars Int

  test = (MkD 3) + (4::Int)     -- REJECTED!
 Consider a finite map, mapping keys to values
 Goal: the data representation of the map
  depends on the type of the key
   Boolean key: store two values (for F,T resp)
   Int key: use a balanced tree
   Pair key (x,y): map x to a finite map from y to
    value; ie use a trie!

 Cannot do this in Haskell...a good program
  that the type checker rejects
data Maybe a = Nothing | Just a

                             Map is indexed by k,
class Key k where            but parametric in its
  data Map k :: * -> *         second argument
  empty :: Map k v
  lookup :: k -> Map k v -> Maybe v
  ...insert, union, etc....
data Maybe a = Nothing | Just a

                             Optional value
class Key k where
                               for False
  data Map k :: * -> *
  empty :: Map k v
  lookup :: k -> Map k v -> Maybe v
  ...insert, union, etc....           Optional value
                                            for True
instance Key Bool where
  data Map Bool v = MB (Maybe v) (Maybe v)
  empty = MB Nothing Nothing
  lookup True (MB _ mt) = mt
  lookup False (MB mf _) = mf
data Maybe a = Nothing | Just a

class Key k where
                                      Two-level
  data Map k :: * -> *
                                        map
  empty :: Map k v
  lookup :: k -> Map k v -> Maybe v               Two-level
  ...insert, union, etc....                        lookup

instance (Key a, Key b) => Key (a,b) where
  data Map (a,b) v = MP (Map a (Map b v))
  empty = MP empty
  lookup (ka,kb) (MP m) = case lookup ka m of
                            Nothing -> Nothing
                            Just m2 -> lookup kb m2

 See paper for lists as keys: arbitrary depth tries
 Goal: the data representation of the map
  depends on the type of the key
   Boolean key: SUM
   Pair key (x,y): PRODUCT
   List key [x]: SUM of PRODUCT + RECURSION

 Easy to extend to other types at will
Client               Server

 addServer :: In Int (In Int (Out Int End))
  addClient :: Out Int (Out Int (In Int End))
 Type of the process expresses its protocol
 Client and server should have dual protocols:
     run addServer addClient          -- OK!
     run addServer addServer          -- BAD!
Client              Server

 addServer :: In Int (In Int (Out Int End))
  addClient :: Out Int (Out Int (In Int End))

   data In v p = In (v -> p)
   data Out v p = Out v p
   data End     = End


          NB punning
data In v p = In (v -> p)
 data Out v p = Out v p
 data End     = End



addServer :: In Int (In Int (Out Int End))
addServer = In (x -> In (y ->
            Out (x + y) End))


 Nothing fancy here
 addClient is similar
run :: ??? -> ??? -> End

       A process      A co-process


class Process p where
  type Co p
  run :: p -> Co p -> End

 Same deal as before: Co is a type-level
  function that transforms a process type into
  its dual
class Process p where       data In v p = In (v -> p)
  type Co p                 data Out v p = Out v p
  run :: p -> Co p -> End   data End     = End


instance Process p => Process (In v p) where
  type Co (In v p) = Out v (Co p)
  run (In vp) (Out v p) = run (vp v) p

instance Process p => Process (Out v p) where
  type Co (Out v p) = In v (Co p)
  run (Out v p) (In vp) = run p (vp v)


             Just the obvious thing really
 The hoary printf chestnut
  printf “Name:%s, Age:%i” :: String -> Int -> String
    Can’t do that, but we can do this:
   printf (lit “Name:” <> string <> lit “, Age:” <> int)
     :: String -> Int -> String

 Machine address computation
  add :: Pointer n -> Offset m -> Pointer (GCD n m)
 Tracking state using Hoare triples
 acquire :: (Get n p ~ Unlocked)
         => Lock n -> M p (Set n p Locked) ()


       Lock-state before                  Lock-state after
   Types have made a huge contribution
     Theorem provers
                                     to this ideal
   Powerful, but
   • Substantial manual             More sophisticated type systems
     assistance required             threaten both Happy Properties:
   • PhD absolutely essential
     (100s of daily users)           1.   Automation is harder
                                     2.   The types are more complicated
                                          (MSc required)
                                    Some complications (2) are exactly
Today’s                              due to ad-hoc restrictions to ensure
experiment                           full automation
                                    At some point it may be best to say
       Type systems
                                     “enough fooling around: just use Coq”.
  Weak, but
  • Automatically checked            But we aren’t there yet
  • No PhD required                 Haskell is a great place to play this
    (1000,000s of daily users)       game

More Related Content

What's hot

3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
Sergey Bandysik
 
Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Bryan O'Sullivan
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
Hermann Hueck
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
HelpWithAssignment.com
 
Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Bryan O'Sullivan
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
 
Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and Cats
Philip Schwarz
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Bryan O'Sullivan
 
C# programming
C# programming C# programming
C# programming
umesh patil
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
John De Goes
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Philip Schwarz
 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)stasimus
 
C# Language Overview Part I
C# Language Overview Part IC# Language Overview Part I
C# Language Overview Part IDoncho Minkov
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
Tom Flaherty
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
EasyStudy3
 
Abstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generatorsAbstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generators
Philip Schwarz
 

What's hot (19)

3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
 
Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Real World Haskell: Lecture 5
Real World Haskell: Lecture 5
 
Lezione03
Lezione03Lezione03
Lezione03
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and Cats
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6
 
C# programming
C# programming C# programming
C# programming
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
 
C# Language Overview Part I
C# Language Overview Part IC# Language Overview Part I
C# Language Overview Part I
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Abstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generatorsAbstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generators
 
Core C#
Core C#Core C#
Core C#
 

Viewers also liked

Beyond Mere Actors
Beyond Mere ActorsBeyond Mere Actors
Beyond Mere Actors
Boston Area Scala Enthusiasts
 
Compositional I/O Stream in Scala
Compositional I/O Stream in ScalaCompositional I/O Stream in Scala
Compositional I/O Stream in Scala
C4Media
 
Reasonable RPC with Remotely
Reasonable RPC with RemotelyReasonable RPC with Remotely
Reasonable RPC with Remotely
Timothy Perrett
 
Purely Functional I/O
Purely Functional I/OPurely Functional I/O
Purely Functional I/O
C4Media
 
Peyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futurePeyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_future
Takayuki Muranushi
 
MongoDB as Search Engine Repository @ MongoTokyo2011
MongoDB as Search Engine Repository @ MongoTokyo2011MongoDB as Search Engine Repository @ MongoTokyo2011
MongoDB as Search Engine Repository @ MongoTokyo2011
Preferred Networks
 
Succinct Data Structure for Analyzing Document Collection
Succinct Data Structure for Analyzing Document CollectionSuccinct Data Structure for Analyzing Document Collection
Succinct Data Structure for Analyzing Document Collection
Preferred Networks
 
オンライン凸最適化と線形識別モデル学習の最前線_IBIS2011
オンライン凸最適化と線形識別モデル学習の最前線_IBIS2011オンライン凸最適化と線形識別モデル学習の最前線_IBIS2011
オンライン凸最適化と線形識別モデル学習の最前線_IBIS2011Preferred Networks
 
LCCC2010:Learning on Cores, Clusters and Cloudsの解説
LCCC2010:Learning on Cores,  Clusters and Cloudsの解説LCCC2010:Learning on Cores,  Clusters and Cloudsの解説
LCCC2010:Learning on Cores, Clusters and Cloudsの解説
Preferred Networks
 
ウェーブレット木の世界
ウェーブレット木の世界ウェーブレット木の世界
ウェーブレット木の世界
Preferred Networks
 
tensor-decomposition
tensor-decompositiontensor-decomposition
tensor-decompositionKenta Oono
 
Jubatusにおける大規模分散オンライン機械学習
Jubatusにおける大規模分散オンライン機械学習Jubatusにおける大規模分散オンライン機械学習
Jubatusにおける大規模分散オンライン機械学習Preferred Networks
 
bigdata2012ml okanohara
bigdata2012ml okanoharabigdata2012ml okanohara
bigdata2012ml okanohara
Preferred Networks
 
MapReduceによる大規模データを利用した機械学習
MapReduceによる大規模データを利用した機械学習MapReduceによる大規模データを利用した機械学習
MapReduceによる大規模データを利用した機械学習
Preferred Networks
 
大規模データ時代に求められる自然言語処理
大規模データ時代に求められる自然言語処理大規模データ時代に求められる自然言語処理
大規模データ時代に求められる自然言語処理
Preferred Networks
 
文法圧縮入門:超高速テキスト処理のためのデータ圧縮(NLP2014チュートリアル)
文法圧縮入門:超高速テキスト処理のためのデータ圧縮(NLP2014チュートリアル)文法圧縮入門:超高速テキスト処理のためのデータ圧縮(NLP2014チュートリアル)
文法圧縮入門:超高速テキスト処理のためのデータ圧縮(NLP2014チュートリアル)
Shirou Maruyama
 
bigdata2012nlp okanohara
bigdata2012nlp okanoharabigdata2012nlp okanohara
bigdata2012nlp okanohara
Preferred Networks
 

Viewers also liked (20)

Beyond Mere Actors
Beyond Mere ActorsBeyond Mere Actors
Beyond Mere Actors
 
Compositional I/O Stream in Scala
Compositional I/O Stream in ScalaCompositional I/O Stream in Scala
Compositional I/O Stream in Scala
 
Reasonable RPC with Remotely
Reasonable RPC with RemotelyReasonable RPC with Remotely
Reasonable RPC with Remotely
 
Purely Functional I/O
Purely Functional I/OPurely Functional I/O
Purely Functional I/O
 
Peyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futurePeyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_future
 
MongoDB as Search Engine Repository @ MongoTokyo2011
MongoDB as Search Engine Repository @ MongoTokyo2011MongoDB as Search Engine Repository @ MongoTokyo2011
MongoDB as Search Engine Repository @ MongoTokyo2011
 
jubatus pressrelease
jubatus pressreleasejubatus pressrelease
jubatus pressrelease
 
Succinct Data Structure for Analyzing Document Collection
Succinct Data Structure for Analyzing Document CollectionSuccinct Data Structure for Analyzing Document Collection
Succinct Data Structure for Analyzing Document Collection
 
オンライン凸最適化と線形識別モデル学習の最前線_IBIS2011
オンライン凸最適化と線形識別モデル学習の最前線_IBIS2011オンライン凸最適化と線形識別モデル学習の最前線_IBIS2011
オンライン凸最適化と線形識別モデル学習の最前線_IBIS2011
 
rcast_20140411
rcast_20140411rcast_20140411
rcast_20140411
 
Herd
HerdHerd
Herd
 
LCCC2010:Learning on Cores, Clusters and Cloudsの解説
LCCC2010:Learning on Cores,  Clusters and Cloudsの解説LCCC2010:Learning on Cores,  Clusters and Cloudsの解説
LCCC2010:Learning on Cores, Clusters and Cloudsの解説
 
ウェーブレット木の世界
ウェーブレット木の世界ウェーブレット木の世界
ウェーブレット木の世界
 
tensor-decomposition
tensor-decompositiontensor-decomposition
tensor-decomposition
 
Jubatusにおける大規模分散オンライン機械学習
Jubatusにおける大規模分散オンライン機械学習Jubatusにおける大規模分散オンライン機械学習
Jubatusにおける大規模分散オンライン機械学習
 
bigdata2012ml okanohara
bigdata2012ml okanoharabigdata2012ml okanohara
bigdata2012ml okanohara
 
MapReduceによる大規模データを利用した機械学習
MapReduceによる大規模データを利用した機械学習MapReduceによる大規模データを利用した機械学習
MapReduceによる大規模データを利用した機械学習
 
大規模データ時代に求められる自然言語処理
大規模データ時代に求められる自然言語処理大規模データ時代に求められる自然言語処理
大規模データ時代に求められる自然言語処理
 
文法圧縮入門:超高速テキスト処理のためのデータ圧縮(NLP2014チュートリアル)
文法圧縮入門:超高速テキスト処理のためのデータ圧縮(NLP2014チュートリアル)文法圧縮入門:超高速テキスト処理のためのデータ圧縮(NLP2014チュートリアル)
文法圧縮入門:超高速テキスト処理のためのデータ圧縮(NLP2014チュートリアル)
 
bigdata2012nlp okanohara
bigdata2012nlp okanoharabigdata2012nlp okanohara
bigdata2012nlp okanohara
 

Similar to Peyton jones-2009-fun with-type_functions-slide

types, types, types
types, types, typestypes, types, types
types, types, types
Fronx Wurmus
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
aleks-f
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
Functional programming in kotlin with Arrow [Sunnytech 2018]
Functional programming in kotlin with Arrow [Sunnytech 2018]Functional programming in kotlin with Arrow [Sunnytech 2018]
Functional programming in kotlin with Arrow [Sunnytech 2018]
Emmanuel Nhan
 
Pharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkPharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkSerge Stinckwich
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
Daniele Pozzobon
 
PPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptxPPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptx
tcsonline1222
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
simenehanmut
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
Arockia Abins
 
MODULE. .pptx
MODULE.                              .pptxMODULE.                              .pptx
MODULE. .pptx
Alpha337901
 
ATS Programming
ATS ProgrammingATS Programming
ATS Programming
Zhiqiang Ren
 
Google Go For Ruby Hackers
Google Go For Ruby HackersGoogle Go For Ruby Hackers
Google Go For Ruby Hackers
Eleanor McHugh
 
PYTHON
PYTHONPYTHON
PYTHON
JOHNYAMSON
 
MTL Versus Free
MTL Versus FreeMTL Versus Free
MTL Versus Free
John De Goes
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingTip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python Typing
Patrick Viafore
 
Demystifying Type Class derivation with Shapeless
Demystifying Type Class derivation with ShapelessDemystifying Type Class derivation with Shapeless
Demystifying Type Class derivation with Shapeless
Yurii Ostapchuk
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
romanandreg
 
Python basics
Python basicsPython basics
Python basics
Manisha Gholve
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
MKalpanaDevi
 

Similar to Peyton jones-2009-fun with-type_functions-slide (20)

types, types, types
types, types, typestypes, types, types
types, types, types
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Functional programming in kotlin with Arrow [Sunnytech 2018]
Functional programming in kotlin with Arrow [Sunnytech 2018]Functional programming in kotlin with Arrow [Sunnytech 2018]
Functional programming in kotlin with Arrow [Sunnytech 2018]
 
Pharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkPharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source Smalltalk
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
 
PPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptxPPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptx
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
MODULE. .pptx
MODULE.                              .pptxMODULE.                              .pptx
MODULE. .pptx
 
ATS Programming
ATS ProgrammingATS Programming
ATS Programming
 
Google Go For Ruby Hackers
Google Go For Ruby HackersGoogle Go For Ruby Hackers
Google Go For Ruby Hackers
 
PYTHON
PYTHONPYTHON
PYTHON
 
MTL Versus Free
MTL Versus FreeMTL Versus Free
MTL Versus Free
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingTip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python Typing
 
Demystifying Type Class derivation with Shapeless
Demystifying Type Class derivation with ShapelessDemystifying Type Class derivation with Shapeless
Demystifying Type Class derivation with Shapeless
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Python basics
Python basicsPython basics
Python basics
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 

Recently uploaded

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 

Recently uploaded (20)

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 

Peyton jones-2009-fun with-type_functions-slide

  • 1. Simon Peyton Jones (Microsoft Research) Chung-Chieh Shan (Rutgers University) Oleg Kiselyov (Fleet Numerical Meteorology and Oceanography Center) Tony Hoare’s 75th birthday celebration, April 2009
  • 2.  “Program correctness is a basic scientific ideal for Computer Science”  “The most widely used tools [in pursuit of correctness] concentrate on the detection of programming errors, widely known as bugs. Foremost among these [tools] are modern compilers for strongly typed languages”  “Like insects that carry disease, the least efficient way of eradicating program bugs is by squashing them one by one. The only sure safeguard against attack is to pursue the ideal of not making the errors in the first place.” “The ideal of program correctness”, Tony Hoare, BCS lecture and debate, Oct 2006
  • 3.  Static typing eradicates whole species of bugs  The static type of a function is a partial specification: its says something (but not too much) about what the function does reverse :: [a] -> [a] Increasingly precise specification The spectrum of confidence Increasing confidence that the program does what you want
  • 4.  The static type of a function is like a weak specification: its says something (but not too much) about what the function does reverse :: [a] -> [a]  Static typing is by far the most widely-used program verification technology in use today: particularly good cost/benefit ratio  Lightweight (so programmers use them)  Machine checked (fully automated, every compilation)  Ubiquitous (so programmers can’t avoid them)
  • 5.  Static typing eradicates whole species of bugs  Static typing is by far the most widely-used program verification technology in use today: particularly good cost/benefit ratio Increasingly precise specification The spectrum of confidence Hammer Increasing (cheap, easy confidence that the Tactical nuclear weapon to use, (expensive, needs a trained program does what limited user, but very effective effectivenes) you want indeed)
  • 6.  The type system designer seeks to  Retain the Joyful Properties of types  While also:  making more good programs pass the type checker  making fewer bad programs pass the type checker
  • 7. Programs that All programs work Programs that are well typed Make this bit bigger!
  • 8.  The type system designer seeks to retain the Joyful Properties of types  While also:  making more good programs pass the type checker  making fewer bad programs pass the type checker  One such endeavour: Extend Haskell with Indexed type families
  • 9.  The type system designer seeks to retain the Joyful Properties of types I fear that  While also: Haskell is doomed to  making more good programs pass the type checker succeed  making fewer bad programs pass the type checker  One such endeavour: Tony Hoare Extend Haskell with (1990) Indexed type families
  • 10. Class decl gives type signature of each method class Num a where (+), (*) :: a -> a -> a negate :: a -> a Instance decl gives a square :: Num a => a -> a “witness” for each square x = x*x method, matching the signature instance Num Int where (+) = plusInt (*) = mulInt negate = negInt plusInt :: Int -> Int -> Int mulInt :: Int -> Int -> Int negInt :: Int -> Int test = square 4 + 5 :: Int
  • 11. plusInt :: Int -> Int -> Int plusFloat :: Float -> Float -> Float intToFloat :: Int -> Float class GNum a b where (+) :: a -> b -> ??? instance GNum Int Int where (+) x y = plusInt x y instance GNum Int Float where (+) x y = plusFloat (intToFloat x) y test1 = (4::Int) + (5::Int) test2 = (4::Int) + (5::Float) Allowing more good programs
  • 12. class GNum a b where (+) :: a -> b -> ???  Result type of (+) is a function of the argument types SumTy is an associated type of class GNum a b where class GNum type SumTy a b :: * (+) :: a -> b -> SumTy a b  Each method gets a type signature  Each associated type gets a kind signature
  • 13. class GNum a b where type SumTy a b :: * (+) :: a -> b -> SumTy a b  Each instance declaration gives a “witness” for SumTy, matching the kind signature instance GNum Int Int where type SumTy Int Int = Int (+) x y = plusInt x y instance GNum Int Float where type SumTy Int Float = Float (+) x y = plusFloat (intToFloat x) y
  • 14. class GNum a b where type SumTy a b :: * instance GNum Int Int where type SumTy Int Int = Int :: * instance GNum Int Float where type SumTy Int Float = Float  SumTy is a type-level function  The type checker simply rewrites  SumTy Int Int --> Int  SumTy Int Float --> Float whenever it can  But (SumTy t1 t2) is still a perfectly good type, even if it can’t be rewritten. For example: data T a b = MkT a b (SumTy a b)
  • 15.  Simply omit instances for incompatible types newtype Dollars = MkD Int instance GNum Dollars Dollars where type SumTy Dollars Dollars = Dollars (+) (MkD d1) (MkD d2) = MkD (d1+d2) -- No instance GNum Dollars Int test = (MkD 3) + (4::Int) -- REJECTED!
  • 16.  Consider a finite map, mapping keys to values  Goal: the data representation of the map depends on the type of the key  Boolean key: store two values (for F,T resp)  Int key: use a balanced tree  Pair key (x,y): map x to a finite map from y to value; ie use a trie!  Cannot do this in Haskell...a good program that the type checker rejects
  • 17. data Maybe a = Nothing | Just a Map is indexed by k, class Key k where but parametric in its data Map k :: * -> * second argument empty :: Map k v lookup :: k -> Map k v -> Maybe v ...insert, union, etc....
  • 18. data Maybe a = Nothing | Just a Optional value class Key k where for False data Map k :: * -> * empty :: Map k v lookup :: k -> Map k v -> Maybe v ...insert, union, etc.... Optional value for True instance Key Bool where data Map Bool v = MB (Maybe v) (Maybe v) empty = MB Nothing Nothing lookup True (MB _ mt) = mt lookup False (MB mf _) = mf
  • 19. data Maybe a = Nothing | Just a class Key k where Two-level data Map k :: * -> * map empty :: Map k v lookup :: k -> Map k v -> Maybe v Two-level ...insert, union, etc.... lookup instance (Key a, Key b) => Key (a,b) where data Map (a,b) v = MP (Map a (Map b v)) empty = MP empty lookup (ka,kb) (MP m) = case lookup ka m of Nothing -> Nothing Just m2 -> lookup kb m2 See paper for lists as keys: arbitrary depth tries
  • 20.  Goal: the data representation of the map depends on the type of the key  Boolean key: SUM  Pair key (x,y): PRODUCT  List key [x]: SUM of PRODUCT + RECURSION  Easy to extend to other types at will
  • 21. Client Server  addServer :: In Int (In Int (Out Int End)) addClient :: Out Int (Out Int (In Int End))  Type of the process expresses its protocol  Client and server should have dual protocols: run addServer addClient -- OK! run addServer addServer -- BAD!
  • 22. Client Server  addServer :: In Int (In Int (Out Int End)) addClient :: Out Int (Out Int (In Int End)) data In v p = In (v -> p) data Out v p = Out v p data End = End NB punning
  • 23. data In v p = In (v -> p) data Out v p = Out v p data End = End addServer :: In Int (In Int (Out Int End)) addServer = In (x -> In (y -> Out (x + y) End))  Nothing fancy here  addClient is similar
  • 24. run :: ??? -> ??? -> End A process A co-process class Process p where type Co p run :: p -> Co p -> End  Same deal as before: Co is a type-level function that transforms a process type into its dual
  • 25. class Process p where data In v p = In (v -> p) type Co p data Out v p = Out v p run :: p -> Co p -> End data End = End instance Process p => Process (In v p) where type Co (In v p) = Out v (Co p) run (In vp) (Out v p) = run (vp v) p instance Process p => Process (Out v p) where type Co (Out v p) = In v (Co p) run (Out v p) (In vp) = run p (vp v) Just the obvious thing really
  • 26.  The hoary printf chestnut printf “Name:%s, Age:%i” :: String -> Int -> String  Can’t do that, but we can do this: printf (lit “Name:” <> string <> lit “, Age:” <> int) :: String -> Int -> String  Machine address computation add :: Pointer n -> Offset m -> Pointer (GCD n m)  Tracking state using Hoare triples acquire :: (Get n p ~ Unlocked) => Lock n -> M p (Set n p Locked) () Lock-state before Lock-state after
  • 27. Types have made a huge contribution Theorem provers to this ideal Powerful, but • Substantial manual  More sophisticated type systems assistance required threaten both Happy Properties: • PhD absolutely essential (100s of daily users) 1. Automation is harder 2. The types are more complicated (MSc required)  Some complications (2) are exactly Today’s due to ad-hoc restrictions to ensure experiment full automation  At some point it may be best to say Type systems “enough fooling around: just use Coq”. Weak, but • Automatically checked But we aren’t there yet • No PhD required  Haskell is a great place to play this (1000,000s of daily users) game