Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Haskell Types Revisited

Bucharest FP
February 25, 2015

Haskell Types Revisited

Bucharest FP

February 25, 2015
Tweet

More Decks by Bucharest FP

Other Decks in Programming

Transcript

  1. Haskell Types Revisited Lucian Mogosanu 25.02.2015

  2. Type systems “Source code is for humans to read, and

    only incidentally for machines to run.” Tools for abstraction Tools for documentation Safeguards against errors
  3. “Advanced” type systems Curry-Howard isomorphism: Proofs as programs Propositions as

    types
  4. Haskell typing philosophy Strong Static Algebraic “If it passes the

    type checker, then it’s correct”
  5. Primitive types 3 :: Int 120894192912541294198294982 :: Integer 3.14 ::

    Float a :: Char "The cake is a lie" :: String True :: Bool
  6. Basic type constructors data Void data Unit = MkUnit data

    Bool = False | True data Kg = MkKg Int -- newtype?
  7. Canonical types data Pair a b = Pair a b

    -- (a, b) data Either a b = Left a | Right b type Maybe a = Either Unit a -- Nothing | Just a data Identity a = Identity a data Const a b = Const a
  8. Recursive data structures data Nat = Z | S Nat

    data List a = Empty | Cons a (List a)
  9. Digression: type classes class Eq a where (==) :: a

    -> a -> Bool instance Eq Bool where True == True = True False == False = True _ == _ = False
  10. Digression: kinds Types also have types They are called kinds

    > :k Bool Bool :: * > :k List List :: * -> * > :k List Int List Int :: * Well-formed typed expressions have the kind *
  11. Type-level numbers data Z data S n class Card n

    where instance Card Z where instance Card n => Card (S n) where
  12. Fixed-length lists newtype Vector n a = Vector { fromVect

    :: List a } Vector constructor is not sufficient Use smart constructors
  13. Fixed-length lists: smart constructors newtype Vector n a = Vector

    { fromVect :: List a } vnil :: Vector Z a vnil = Vector Empty vcons :: Card n => a -> Vector n a -> Vector (S n) a vcons x (Vector xs) = Vector (x Cons xs)
  14. Fixed-length lists: useful functions head and tail are type safe

    vhead :: Card n => Vector (S n) a -> a vhead (Vector (Cons x _)) = x vtail :: Card n => Vector (S n) a -> Vector n a vtail (Vector (Cons _ xs)) = Vector xs
  15. Fixed-length lists: problems vappend? vappend :: Card n => Vector

    n a -> Vector m a -> Vector (n + m) a Type family for Z and S n Undecidable instances
  16. Conclusion hackage.haskell.org/package/mono-traversable Dependently-typed languages: Idris, Agda, Coq Require (mostly) manual

    typechecking!