6. Problem
first :: [Int] -> Int
first arr = arr !! 0
public int first(int[] arr)
{
return arr[0];
}
def first(arr) do
List.first arr
end
anything → anything (or runtime error)
array or null → int (or runtime error)
array → int (or runtime error)
10. 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)
11. 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
12. 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
13. Concatenation
(++) : Vect n a -> Vect m a -> Vect (n + m) a
(++) Nil ys = ys
(++) (x :: xs) ys = x :: xs ++ ys
14. Concatenation
(++) : 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
* Not actual error message
23. Type-safe Printf
printf : (str : String) -> PrintfType (toFormat (unpack str))
toFormat : List Char -> Format
PrintfType : Format -> Type
24. Type-safe Printf
data Format = Number Format
| Str Format
| Lit Char Format
| End
> toFormat (unpack "a%s")
Lit 'a' (Str End) : Format
> toFormat (unpack "%d")
Number End
25. Type-safe Printf
toFormat : (xs : List Char) -> Format
toFormat [] = End
toFormat ('%' :: 's' :: xs) = Str (toFormat xs)
toFormat ('%' :: 'd' :: xs) = Number (toFormat xs)
toFormat (x :: xs) = Lit x (toFormat xs)
26. Type-safe Printf
PrintfType : Format -> Type
PrintfType (Number fmt) = Int -> PrintfType fmt
PrintfType (Str fmt) = String -> PrintfType fmt
PrintfType (Lit x fmt) = PrintfType fmt
PrintfType End = String
29. 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
30. Proofs
Theorem: 4 is even
0 is even
0 + 2 is even
(0 + 2) + 2 is even
fourIsEven : Even 4
fourIsEven = ES (ES EZ)
Idris