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. 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
  2. Primitive types 3 :: Int 120894192912541294198294982 :: Integer 3.14 ::

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

    Bool = False | True data Kg = MkKg Int -- newtype?
  4. 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
  5. Recursive data structures data Nat = Z | S Nat

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

    -> a -> Bool instance Eq Bool where True == True = True False == False = True _ == _ = False
  7. 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 *
  8. Type-level numbers data Z data S n class Card n

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

    :: List a } Vector constructor is not sufficient Use smart constructors
  10. 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)
  11. 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
  12. 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