Wheat Wizard
Wheat Wizard

Reputation: 4219

Index a Heterogeneous List

I built a heterogeneous List in Haskell using some type level programming.

data HList a where
  Singleton :: HList '[]
  Cons :: h -> HList t -> HList (h ': t)

Now I would like to be able to index this list, however there are some problems with types that are making this very difficult for me. I can get the head or tail of this list very easily

head :: HList (h ': t) -> h
head (Cons a _) = a

tail :: HList (h ': t) -> HList t
tail (Cons _ b) = b

However indexing the list is very different because the type of the output depends on what index we pass. So naïvely our type would look something like:

fromIndex :: (Num a) => a -> (HList b) -> ???

However determining the ??? is rather hard. So instead of taking a Num we are going to have to take something else. My idea (code below) was to make a new Natural and an IndexType class with a functional dependency which would allow us to find the type of the result just from the types of the input.

{-# Language GADTs, DataKinds, TypeOperators, FunctionalDependencies, FlexibleInstances, FlexibleContexts, UndecidableInstances #-}

data Nat = Z | S Nat

data Natural a where
  Zero :: Natural 'Z
  Succ :: Natural a -> Natural ('S a)

data HList a where
 Singleton :: HList '[]
 Cons :: h -> HList t -> HList (h ': t)

class IndexType a b c | a b -> c
instance IndexType (Natural 'Z) (HList (h ': t)) h
instance IndexType (Natural n) (HList t) a => IndexType (Natural ('S n)) (HList (h ': t)) a

fromIndex :: (IndexType (Natural n) (HList l) a) => (Natural n) -> (HList l) -> a
fromIndex (Zero) (Cons x Singleton) = x
fromIndex (Succ a) (Cons _ (xs)) = fromIndex a xs

Our IndexType class does work. If I test just the type class

class Test a | -> a
  where test :: a
instance (IndexType (Natural ('S ('S ('S 'Z)))) (HList (Int ': String ': Char ': (Int -> String) ': Int ': '[])) a) => Test a

We get the correct result:

*Main> :t test
test :: Int -> String

However ghc is unable to verify our type signature and we get the rather monolithic error:

test.hs:28:39: error:
    • Could not deduce: h ~ a
      from the context: n ~ 'Z
        bound by a pattern with constructor: Zero :: Natural 'Z,
                 in an equation for ‘fromIndex’
        at test.hs:28:12-15
      or from: l ~ (h : t)
        bound by a pattern with constructor:
                   Cons :: forall h (t :: [*]). h -> HList t -> HList (h : t),
                 in an equation for ‘fromIndex’
        at test.hs:28:19-34
      or from: t ~ '[]
        bound by a pattern with constructor: Singleton :: HList '[],
                 in an equation for ‘fromIndex’
        at test.hs:28:26-34
      ‘h’ is a rigid type variable bound by
        a pattern with constructor:
          Cons :: forall h (t :: [*]). h -> HList t -> HList (h : t),
        in an equation for ‘fromIndex’
        at test.hs:28:19-34
      ‘a’ is a rigid type variable bound by
        the type signature for:
          fromIndex :: forall (n :: Nat) (l :: [*]) a.
                       IndexType (Natural n) (HList l) a =>
                       Natural n -> HList l -> a
        at test.hs:27:1-81
    • In the expression: x
      In an equation for ‘fromIndex’:
          fromIndex (Zero) (Cons x Singleton) = x
    • Relevant bindings include
        x :: h (bound at test.hs:28:24)
        fromIndex :: Natural n -> HList l -> a (bound at test.hs:28:1)
   |
28 | fromIndex (Zero) (Cons x Singleton) = x
   |                                       ^

test.hs:29:36: error:
    • Could not deduce (IndexType (Natural a1) (HList t) a)
        arising from a use of ‘fromIndex’
      from the context: IndexType (Natural n) (HList l) a
        bound by the type signature for:
                   fromIndex :: forall (n :: Nat) (l :: [*]) a.
                                IndexType (Natural n) (HList l) a =>
                                Natural n -> HList l -> a
        at test.hs:27:1-81
      or from: n ~ 'S a1
        bound by a pattern with constructor:
                   Succ :: forall (a :: Nat). Natural a -> Natural ('S a),
                 in an equation for ‘fromIndex’
        at test.hs:29:12-17
      or from: l ~ (h : t)
        bound by a pattern with constructor:
                   Cons :: forall h (t :: [*]). h -> HList t -> HList (h : t),
                 in an equation for ‘fromIndex’
        at test.hs:29:21-31
    • In the expression: fromIndex a xs
      In an equation for ‘fromIndex’:
          fromIndex (Succ a) (Cons _ (xs)) = fromIndex a xs
   |
29 | fromIndex (Succ a) (Cons _ (xs)) = fromIndex a xs
   |                                    ^^^^^^^^^^^^^^
Failed, no modules loaded.

Can the index function be built? Is there a way to get GHC to deduce that my type signature is correct?

Upvotes: 1

Views: 303

Answers (2)

HTNW
HTNW

Reputation: 29193

I'd define the following:

-- The type of numbers n such that xs !! n = x
-- Compare to Nat
data Elem (x :: k) (xs :: [k]) where
  Here  :: Elem x (x : xs)
  There :: Elem x xs -> Elem x (y : xs)

And then you find that HLists are isomorphic to "indexing functions" (in the same way Vect n a is isomorphic to Fin n -> a) involving this type:

indexHList :: forall xs. HList xs -> (forall x. Elem x xs -> x)
indexHList (Cons x _) Here = x
indexHList (Cons _ xs) (There i) = indexHList xs i
indexHList Singleton impossible = case impossible of {}

-- unindexHList ::ish forall xs. (forall x. Elem x xs -> x) -> HList xs
-- is a bit more work (and doesn't really have that type)
-- but is conceptually the other half of the isomorphism.

Usage:

xs :: HList [Int, String, HList '[]]
xs = Cons 5 $ Cons "hello" $ Cons Singleton $ Singleton
-- Here :: Elem Int (Int:_)
indexHList xs Here == 5
-- Here :: Elem String (String:_)
-- There Here :: Elem String (_:String:_)
indexHList xs (There Here) == "hello"

Compared to your class-based technique, Elem x xs is basically exists n. (Natural n, IndexType (Natural n) (HList xs) x). Being a data type that you can inspect, it is easier to manipulate than the class.

Upvotes: 2

Alec
Alec

Reputation: 32339

The cases of your fromIndex have different types! They need to be inside the instances

class IndexType (n :: Nat) (xs :: [Type]) (i :: Type) | n xs -> i where
   fromIndex :: Natural n -> HList xs -> i

 instance IndexType Z (x ': xs) x where
   fromIndex Zero (Cons x _) = x

 instance IndexType n xs a => IndexType (S n) (x ': xs) a where
   fromIndex (Succ n) (Cons _ xs) = fromIndex n xs

(I've shuffled around slightly the type of fromIndex :: Natural n -> HList xs -> i. That doesn't actually change anything - your solution works just as well, albeit with more confusing error messages if you call fromIndex in an unexpected context.)

Upvotes: 3

Related Questions