从普通列表创建索引链接列表

时间:2020-07-15 12:27:45

标签: haskell dependent-type type-level-computation

我目前正在使用索引链接列表。基本数据类型由

给出
data LList (n :: Nat) (a :: Type) where
  Nil  ::LList 0 a
  (:@) ::a -> LList n a -> LList (n + 1) a

我想知道是否可以定义从[]LList的映射吗?

返回类型取决于运行时信息,因为列表的长度当然在编译时不可用。

fromList :: ? => [a] => LList ? a
fromList = undefined

游乐场is available here的完整源代码。

1 个答案:

答案 0 :(得分:2)

是的,只需使用一个存在的。这样会将列表的长度和列表本身包装为一对,但不会在类型中显示其长度。

data SomeLList a = forall n. SomeLList (LList n a)

这表示SomeLList aSomeLList @(n :: Nat) (_ :: LList n a)形式的术语组成。实际上,这种类型等效于[](除了多余的底数和无穷大之外)

fromList :: [a] -> SomeLList a
fromList [] = Nil
fromList (x : xs) | SomeList xs' <- fromList xs = SomeList (x :@ xs)

您可以通过匹配来获得配对中的类型:

something :: [a] -> ()
something xs
  | SomeList xs' <- fromList xs
  = -- here, xs' :: SomeList n xs, where n :: Nat is a new type (invisibly) extracted from the match
    -- currently, we don't know anything about n except its type, but we could e.g. match on xs', which is a GADT and could tell us about n
    ()