实现可扩展记录时编译错误

时间:2018-05-26 15:15:06

标签: idris

我正在玩idris,并试图实现可扩展的记录。

主要目标是保证记录的密钥是唯一的。

例如

("Year" := 1998) +: rnil

是合法的

("Title" := "test") +: ("Year" := 1998) +: rnil

也有效,但

("Year" := "test") +: ("Year" := 1998) +: rnil

无法编译。

我提出了以下实现,编译得很好:

{-
See: http://lpaste.net/104020
  and https://github.com/gonzaw/extensible-records
-}
module Record

import Data.List

%default total

data HList : List Type -> Type where
  Nil : HList []
  (::) : a -> HList xs -> HList (a :: xs)

infix 5 :=

data Field : lbl -> Type -> Type where
  (:=) : (label : lbl) ->
          (value : b) -> Field label b

labelsOf : List (lbl, Type) -> List lbl
labelsOf [] = []
labelsOf ((label, _) :: xs) = label :: labelsOf xs

toFields : List (lbl, Type) -> List Type
toFields [] = []
toFields ((l, t) :: xs) = (Field l t) :: toFields xs

data IsSet : List t -> Type where
  IsSetNil : IsSet []
  IsSetCons : Not (Elem x xs) -> IsSet xs -> IsSet (x :: xs)

data Record : List (lty, Type) -> Type where
  MkRecord : IsSet (labelsOf ts) -> HList (toFields ts) ->
                                    Record ts

infixr 6 +:

rnil : Record []
rnil = MkRecord IsSetNil []

prepend : { label : lbl,
          xs : List (lbl, Type),
          prf : Not (Elem label (labelsOf xs))
        } ->
        Field label t ->
        Record xs ->
        Record ((label, t) :: xs)
prepend {prf} f (MkRecord isSet fs) = MkRecord (IsSetCons prf isSet) (f :: fs)

data IsNo : Dec prop -> Type where
  ItIsNo : IsNo (No y)

(+:) : DecEq lbl =>
  { label : lbl, xs : List (lbl, Type) } ->
  Field label t ->
  Record xs ->
  { auto isno : IsNo (isElem label $ labelsOf xs) } ->
  Record ((label, t) :: xs)

(+:) {label} {xs} f r with (isElem label $ labelsOf xs)
    (+:) { isno = ItIsNo } _ _ | (Yes _) impossible
    (+:) f r | (No no) = prepend {prf = no} f r

有趣的是

  { auto isno : IsNo (isElem label $ labelsOf xs) } ->

这个想法是,如果密钥是唯一的,编译器将琐事地找到IsNo的实例,而如果密钥不是唯一的,那么它就不会被编译。

这适用于那些示例

("Year" := 1998) +: rnil                       -- Compiles fine
("Year" := "test") +: ("Year" := 1998) +: rnil -- fails to compile as expected

但是

("Title" := "test") +: ("Year" := 1998) +: rnil

无法使用以下错误进行编译:

    (input):Type mismatch between
        ("Title" = "Year") -> "Title" = "Year"
and
        ("Title" = "Year") -> Void

我必须承认这个错误令我感到困惑。谁能解释一下这里发生了什么?

1 个答案:

答案 0 :(得分:3)

您似乎是第一个在愤怒中使用DecEq String实例的人,因此,您是第一个发现我们在这里为基元构建证明术语的方式是错的。对于那个很抱歉。好消息是它很容易修复(我刚刚在你的例子中试过它并且它很好),坏消息是你在推动修复后需要git头。

无论如何,我们已经推迟了新的发布。我会在本周末尝试这样做。你的代码对我来说当然很好!