【问题标题】:Non-empty-list comonad非空列表comonad
【发布时间】:2018-03-15 05:05:13
【问题描述】:

我一直在冥想comonads,并且直觉认为非空列表(“完整列表”)是comonads。我在 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

【问题讨论】:

    标签: list idris category-theory comonad


    【解决方案1】:

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

    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))),其中Cons 中的f 指的是nesting_extend 的参数f

    【讨论】:

    • 很好的答案;不仅解决了我的问题,而且加深了我对 Idris 领域最困难的理解。让我意识到我也可以用cong 来写我拥有rewrite ... in ... 的部分。谢谢!
    猜你喜欢
    • 2020-03-26
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 2022-01-23
    • 2015-02-01
    • 2021-08-22
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多