my blog lives here now
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

331 lines
12 KiB

7 years ago
  1. ---
  2. title: Dependent types in Haskell - Sort of
  3. date: August 23, 2016
  4. ---
  5. **Warning**: An intermediate level of type-fu is necessary for understanding
  6. *this post.
  7. The glorious Glasgow Haskell Compilation system, since around version 6.10 has
  8. had support for indexed type familes, which let us represent functional
  9. relationships between types. Since around version 7, it has also supported
  10. datatype-kind promotion, which lifts arbitrary data declarations to types. Since
  11. version 8, it has supported an extension called `TypeInType`, which unifies the
  12. kind and type level.
  13. With this in mind, we can implement the classical dependently-typed example:
  14. Length-indexed lists, also called `Vectors`{.haskell}.
  15. ----
  16. > {-# LANGUAGE TypeInType #-}
  17. `TypeInType` also implies `DataKinds`, which enables datatype promotion, and
  18. `PolyKinds`, which enables kind polymorphism.
  19. `TypeOperators` is needed for expressing type-level relationships infixly, and
  20. `TypeFamilies` actually lets us define these type-level functions.
  21. > {-# LANGUAGE TypeOperators #-}
  22. > {-# LANGUAGE TypeFamilies #-}
  23. Since these are not simple-kinded types, we'll need a way to set their kind
  24. signatures[^kind] explicitly. We'll also need Generalized Algebraic Data Types
  25. (or GADTs, for short) for defining these types.
  26. > {-# LANGUAGE KindSignatures #-}
  27. > {-# LANGUAGE GADTs #-}
  28. Since GADTs which couldn't normally be defined with regular ADT syntax can't
  29. have deriving clauses, we also need `StandaloneDeriving`.
  30. > {-# LANGUAGE StandaloneDeriving #-}
  31. > module Vector where
  32. > import Data.Kind
  33. ----
  34. Natural numbers
  35. ===============
  36. We could use the natural numbers (and singletons) implemented in `GHC.TypeLits`,
  37. but since those are not defined inductively, they're painful to use for our
  38. purposes.
  39. Recall the definition of natural numbers proposed by Giuseppe Peano in his
  40. axioms: **Z**ero is a natural number, and the **s**uccessor of a natural number
  41. is also a natural number.
  42. If you noticed the bold characters at the start of the words _zero_ and
  43. _successor_, you might have already assumed the definition of naturals to be
  44. given by the following GADT:
  45. < data Nat where
  46. < Z :: Nat
  47. < S :: Nat -> Nat
  48. This is fine if all you need are natural numbers at the _value_ level, but since
  49. we'll be parametrising the Vector type with these, they have to exist at the
  50. type level. The beauty of datatype promotion is that any promoted type will
  51. exist at both levels: A kind with constructors as its inhabitant types, and a
  52. type with constructors as its... constructors.
  53. Since we have TypeInType, this declaration was automatically lifted, but we'll
  54. use explicit kind signatures for clarity.
  55. > data Nat :: Type where
  56. > Z :: Nat
  57. > S :: Nat -> Nat
  58. The `Type` kind, imported from `Data.Kind`, is a synonym for the `*` (which will
  59. eventually replace the latter).
  60. Vectors
  61. =======
  62. Vectors, in dependently-typed languages, are lists that apart from their content
  63. encode their size along with their type.
  64. If we assume that lists can not have negative length, and an empty vector has
  65. length 0, this gives us a nice inductive definition using the natural number
  66. ~~type~~ kind[^kinds]
  67. > 1. An empty vector of `a` has size `Z`{.haskell}.
  68. > 2. Adding an element to the front of a vector of `a` and length `n` makes it
  69. > have length `S n`{.haskell}.
  70. We'll represent this in Haskell as a datatype with a kind signature of `Nat ->
  71. Type -> Type` - That is, it takes a natural number (remember, these were
  72. automatically lifted to kinds), a regular type, and produces a regular type.
  73. Note that, `->` still means a function at the kind level.
  74. > data Vector :: Nat -> Type -> Type where
  75. Or, without use of `Type`,
  76. < data Vector :: Nat -> * -> * where
  77. We'll call the empty vector `Nil`{.haskell}. Remember, it has size
  78. `Z`{.haskell}.
  79. > Nil :: Vector Z a
  80. Also note that type variables are implicit in the presence of kind signatures:
  81. They are assigned names in order of appearance.
  82. Consing onto a vector, represented by the infix constructor `:|`, sets its
  83. length to the successor of the existing length, and keeps the type of elements
  84. intact.
  85. > (:|) :: a -> Vector x a -> Vector (S x) a
  86. Since this constructor is infix, we also need a fixidity declaration. For
  87. consistency with `(:)`, cons for regular lists, we'll make it right-associative
  88. with a precedence of `5`.
  89. > infixr 5 :|
  90. We'll use derived `Show`{.haskell} and `Eq`{.haskell} instances for
  91. `Vector`{.haskell}, for clarity reasons. While the derived `Eq`{.haskell} is
  92. fine, one would prefer a nicer `Show`{.haskell} instance for a
  93. production-quality library.
  94. > deriving instance Show a => Show (Vector n a)
  95. > deriving instance Eq a => Eq (Vector n a)
  96. Slicing up Vectors {#slicing}
  97. ==================
  98. Now that we have a vector type, we'll start out by implementing the 4 basic
  99. operations for slicing up lists: `head`, `tail`, `init` and `last`.
  100. Since we're working with complicated types here, it's best to always use type
  101. signatures.
  102. Head and Tail {#head-and-tail}
  103. -------------
  104. Head is easy - It takes a vector with length `>1`, and returns its first
  105. element. This could be represented in two ways.
  106. < head :: (S Z >= x) ~ True => Vector x a -> a
  107. This type signature means that, if the type-expression `S Z >= x`{.haskell}
  108. unifies with the type `True` (remember - datakind promotion at work), then head
  109. takes a `Vector x a` and returns an `a`.
  110. There is, however, a much simpler way of doing the above.
  111. > head :: Vector (S x) a -> a
  112. That is, head takes a vector whose length is the successor of a natural number
  113. `x` and returns its first element.
  114. The implementation is just as concise as the one for lists:
  115. > head (x :| _) = x
  116. That's it. That'll type-check and compile.
  117. Trying, however, to use that function on an empty vector will result in a big
  118. scary type error:
  119. ```plain
  120. Vector> Vector.head Nil
  121. <interactive>:1:13: error:
  122. • Couldn't match type ‘'Z’ with ‘'S x0’
  123. Expected type: Vector ('S x0) a
  124. Actual type: Vector 'Z a
  125. • In the first argument of ‘Vector.head’, namely ‘Nil’
  126. In the expression: Vector.head Nil
  127. In an equation for ‘it’: it = Vector.head Nil
  128. ```
  129. Simplified, it means that while it was expecting the successor of a natural
  130. number, it got zero instead. This function is total, unlike the one in
  131. `Data.List`{.haskell}, which fails on the empty list.
  132. < head [] = error "Prelude.head: empty list"
  133. < head (x:_) = x
  134. Tail is just as easy, except in this case, instead of discarding the predecessor
  135. of the vector's length, we'll use it as the length of the resulting vector.
  136. This makes sense, as, logically, getting the tail of a vector removes its first
  137. length, thus "unwrapping" a level of `S`.
  138. > tail :: Vector (S x) a -> Vector x a
  139. > tail (_ :| xs) = xs
  140. Notice how neither of these have a base case for empty vectors. In fact, adding
  141. one will not typecheck (with the same type of error - Can't unify `Z`{.haskell}
  142. with `S x`{.haskell}, no matter how hard you try.)
  143. Init {#init}
  144. ----
  145. What does it mean to take the initial of an empty vector? That's obviously
  146. undefined, much like taking the tail of an empty vector. That is, `init` and
  147. `tail` have the same type signature.
  148. > init :: Vector (S x) a -> Vector x a
  149. The `init` of a singleton list is nil. This type-checks, as the list would have
  150. had length `S Z` (that is - 1), and now has length `Z`.
  151. > init (x :| Nil) = Nil
  152. To take the init of a vector with more than one element, all we do is recur on
  153. the tail of the list.
  154. > init (x :| y :| ys) = x :| Vector.init (y :| ys)
  155. That pattern is a bit weird - it's logically equivalent to `(x :|
  156. xs)`{.haskell}. But, for some reason, that doesn't make the typechecker happy,
  157. so we use the long form.
  158. Last {#last}
  159. ----
  160. Last can, much like the list version, be implemented in terms of a left fold.
  161. The type signature is like the one for head, and the fold is the same as that
  162. for lists. The foldable instance for vectors is given [here](#Foldable).
  163. > last :: Vector (S x) a -> a
  164. > last = foldl (\_ x -> x) impossible where
  165. Wait - what's `impossible`? Since this is a fold, we do still need an initial
  166. element - We could use a pointful fold with the head as the starting point, but
  167. I feel like this helps us to understand the power of dependently-typed vectors:
  168. That error will _never_ happen. Ever. That's why it's `impossible`!
  169. > impossible = error "Type checker, you have failed me!"
  170. That's it for the basic vector operations. We can now slice a vector anywhere
  171. that makes sense - Though, there's one thing missing: `uncons`.
  172. Uncons {#uncons}
  173. ------
  174. Uncons splits a list (here, a vector) into a pair of first element and rest.
  175. With lists, this is generally implemented as returning a `Maybe`{.haskell} type,
  176. but since we can encode the type of a vector in it's type, there's no need for
  177. that here.
  178. > uncons :: Vector (S x) a -> (a, Vector x a)
  179. > uncons (x :| xs) = (x, xs)
  180. Mapping over Vectors {#functor}
  181. ====================
  182. We'd like a `map` function that, much like the list equivalent, applies a
  183. function to all elements of a vector, and returns a vector with the same length.
  184. This operation should hopefully be homomorphic: That is, it keeps the structure
  185. of the list intact.
  186. The `base` package has a typeclass for this kind of morphism, can you guess what
  187. it is? If you guessed Functor, then you're right! If you didn't, you might
  188. aswell close the article now - Heavy type-fu inbound, though not right now.
  189. The functor instance is as simple as can be:
  190. > instance Functor (Vector x) where
  191. The fact that functor expects something of kind `* -> *`, we need to give the
  192. length in the instance head - And since we do that, the type checker guarantees
  193. that this is, in fact, a homomorphic relationship.
  194. Mapping over `Nil` just returns `Nil`.
  195. > f `fmap` Nil = Nil
  196. Mapping over a list is equivalent to applying the function to the first element,
  197. then recurring over the tail of the vector.
  198. > f `fmap` (x :| xs) = f x :| (fmap f xs)
  199. We didn't really need an instance of Functor, but I think standalone map is
  200. silly.
  201. Folding Vectors {#foldable}
  202. ===============
  203. The Foldable class head has the same kind signature as the Functor class head:
  204. `(* -> *) -> Constraint` (where `Constraint` is the kind of type classes), that
  205. is, it's defined by the class head
  206. < class Foldable (t :: Type -> Type) where
  207. So, again, the length is given in the instance head.
  208. > instance Foldable (Vector x) where
  209. > foldr f z Nil = z
  210. > foldr f z (x :| xs) = f x $ foldr f z xs
  211. This is _exactly_ the Foldable instance for `[a]`, except the constructors are
  212. different. Hopefully, by now you've noticed that Vectors have the same
  213. expressive power as lists, but with more safety enforced by the type checker.
  214. Conclusion
  215. ==========
  216. Two thousand words in, we have an implementation of functorial, foldable vectors
  217. with implementations of `head`, `tail`, `init`, `last` and `uncons`. Since
  218. going further (implementing `++`, since a Monoid instance is impossible) would
  219. require implementing closed type familes, we'll leave that for next time.
  220. Next time, we'll tackle the implementation of `drop`, `take`, `index` (`!!`, but
  221. for vectors), `append`, `length`, and many other useful list functions.
  222. Eventually, you'd want an implementation of all functions in `Data.List`. We
  223. shall tackle `filter` in a later issue.
  224. [^kind]: You can read about [Kind polymorphism and
  225. Type-in-Type](https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#kind-polymorphism-and-type-in-type)
  226. in the GHC manual.
  227. [^kinds]: The TypeInType extension unifies the type and kind level, but this
  228. article still uses the word `kind` throughout. This is because it's easier to
  229. reason about types, datatype promotion and type familes if you have separate
  230. type and kind levels.