Dependent types allow you to write eliminate a larger class of runtime errors by allowing you to express more invariants at compile time. Idris is one such language.
2. Features
Strictly evaluated purely functional language
Has backends to LLVM, C, Javascript and even Erlang!
Full dependent types with dependent pattern matching
Simple foreign function interface (to C)
Compiler-supported interactive editing: the compiler helps you write code using the types
where clauses, with rule, simple case expressions, pattern matching let and lambda bindings
Dependent records with projection and update
7. Problem
first :: [Int] -> Int
first xs = xs !! 0
public int first(int[] list)
{
return list[0];
}
def first(arr)
arr[0]
end
anything → anything (or runtime error)
array or null → int (or runtime error)
array → int (or runtime error)
8. Problem
● Types don’t capture all the invariants
● Functions work for only a subset of inputs ‒ they are not
total
9. Dependent Types
Dependent Types allow types to depend on their values.
e.g. length of a list can be part of the type of the list
11. Operations
plus : Nat -> Nat -> Nat
plus Z y = y
plus (S k) y = S (plus k y)
0 + y = y
(1 + x) + y = 1 + (x + y)
0 ✕ y = 0
(1 + x) ✕ y = y + (x ✕ y)
mult : Nat -> Nat -> Nat
mult Z y = Z
mult (S k) y = plus y (mult k y)
12. Vectors
data Vect : Nat -> Type -> Type where
Nil : Vect Z a
(::) : a -> Vect k a -> Vect (S k) a
zeroVect : Vect 0 Int
zeroVect = Nil
oneVect : Vect 1 Int
oneVect = 3 :: Nil
threeVect : Vect 3 String
threeVect = "I" :: "hope" :: "i'm not confusing you" :: Nil
13. Solution
first : Vect (S k) a -> a
first (x::xs) = x
Points of Failure:
1. arr is not an array
2. arr is null
3. arr is empty
14. Concatenation
(++) : Vect n a -> Vect m a -> Vect (n + m) a
(++) Nil ys = ys
(++) (x :: xs) ys = x :: xs ++ ys
(++) : Vect n a -> Vect m a -> Vect (n + m) a
(++) Nil ys = ys
(++) (x :: xs) ys = x :: xs ++ xs
Error: Expected Vect (n + m) a; Got Vect (n + n) a
16. elemAt
elemAt : Fin n -> Vect n a -> a
elemAt FZ (x :: xs) = x
elemAt (FS k) (x :: xs) = elemAt k xs
data Fin : Nat -> Type where
FZ : Fin (S k)
FS : Fin k -> Fin (S k)
17. Even Numbers
data Even : Nat -> Type where
EZ : Even Z
ES : Even k -> Even (S (S k))
zeroIsEven : Even 0
zeroIsEven = EZ
twoIsEven : Even 2
twoIsEven = ES EZ
18. Proofs
Theorem: 4 is even
0 is even
0 + 2 is even
(0 + 2) + 2 is even
Proof by Mathematical Induction
fourIsEven : Even 4
fourIsEven = ES (ES EZ)
Idris
20. Equality
data (=) : a -> b -> Type where
Refl : x = x
twoIsTwo : 2 = 2
twoIsTwo = Refl
3Plus2IsFive : 3 + 2 = 5
3Plus2IsFive = Refl
21. Falsity or the Empty Type
disjoint : (n : Nat) -> Z = S n -> Void
disjoint n p = replace {P = disjointTy} p ()
where
disjointTy : Nat -> Type
disjointTy Z = ()
disjointTy (S k) = Void
data Void : Type where