我一直在思考comonads,直觉上说非空列表(“完整列表”)是comonad。我在Idris中构造了一个可行的实现,并尝试证明comonad laws,但未能证明其中一项法律的递归分支。如何证明这一点(?i_do_not_know_how_to_prove_this_if_its_provable漏洞)?或者我对自己的实现是有效的comonad(我看过Haskell NonEmpty comonad实现,似乎与我的实现)是错的吗?

module FullList

%default total

data FullList : Type -> Type where
  Single : a -> FullList a
  Cons : a -> FullList a -> FullList a

extract : FullList a -> a
extract (Single x) = x
extract (Cons x _) = x

duplicate : FullList a -> FullList (FullList a)
duplicate = Single

extend : (FullList a -> b) -> FullList a -> FullList b
extend f (Single x) = Single (f (Single x))
extend f (Cons x y) = Cons (f (Cons x y)) (extend f y)

extend_and_extract_are_inverse : (l : FullList a) -> extend FullList.extract l = l
extend_and_extract_are_inverse (Single x) = Refl
extend_and_extract_are_inverse (Cons x y) = rewrite extend_and_extract_are_inverse y in Refl

comonad_law_1 : (l : FullList a) -> extract (FullList.extend f l) = f l
comonad_law_1 (Single x) = Refl
comonad_law_1 (Cons x y) = Refl

nesting_extend : (l : FullList a) -> extend f (extend g l) = extend (\x => f (extend g x)) l
nesting_extend (Single x) = Refl
nesting_extend (Cons x y) = ?i_do_not_know_how_to_prove_this_if_its_provable

最佳答案

请注意,您的目标具有以下形式:

Cons (f (Cons (g (Cons x y)) (extend g y))) (extend f (extend g y)) =
Cons (f (Cons (g (Cons x y)) (extend g y))) (extend (\x1 => f (extend g x1)) y)

您基本上需要证明尾部相等:
extend f (extend g y) = extend (\x1 => f (extend g x1)) y

但这正是归纳假设(nesting_extend y)所说的!因此,证明很简单:
nesting_extend : (l : FullList a) -> extend f (extend g l) = extend (f . extend g) l
nesting_extend (Single x) = Refl
nesting_extend (Cons x y) = cong $ nesting_extend y

我使用了全等引理cong:
cong : (a = b) -> f a = f b

表示任何函数f将相等的术语映射为相等的术语。

在这里Idris推断fCons (f (Cons (g (Cons x y)) (extend g y))),其中f中的Cons引用nesting_extend的参数f

10-06 03:31