dependent-type - Idris 确定结果向量长度

标签 dependent-type idris

在Idris中,如果我想根据谓词删除一个元素,有filterdropWhiletakeWhile。但是,所有这些函数都返回依赖对 (n : Nat ** Vect n elem)

是否有任何函数返回为 Vect 类型?

我能想到的:

  1. 将依赖对转换为Vect

  2. 实现一个指示转换后长度向量的类型(我想我不知道怎么做),比如HereThere

对于上面的思路,1(对每一个结果都进行转换)或者2(对每一个类型都设计一个表示结果向量的长度),似乎比较繁琐。

有没有更好的方法来实现这种行为?

dropElem : String -> Vect n String -> Vect ?resultLen String

最佳答案

也许这就是您要搜索的内容?

import Data.Vect

count: (ty -> Bool) -> Vect n ty -> Nat
count f [] = 0
count f (x::xs) with (f x)
    | False = count f xs
    | True = 1 + count f xs

%hint
countLemma: {v: Vect n ty} -> count f v `LTE` n
countLemma {v=[]} = LTEZero
countLemma {v=x::xs} {f} with (f x)
    | False = lteSuccRight countLemma
    | True = LTESucc countLemma

filter: (f: ty -> Bool) -> (v: Vect n ty) -> Vect (count f v) ty
filter f [] = []
filter f (x::xs) with (f x)
    | False = filter f xs
    | True = x::filter f xs

然后你可以这样做:

dropElem: (s: String) -> (v: Vect n String) -> Vect (count ((/=) s) v) String
dropElem s = filter ((/=) s)

您甚至可以重用现有的filter 实现:

count: (ty -> Bool) -> Vect n ty -> Nat
count f v = fst $ filter f v

filter: (f: ty -> Bool) -> (v: Vect n ty) -> Vect (count f v) ty
filter f v = snd $ filter f v

关于dependent-type - Idris 确定结果向量长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46526503/

相关文章:

types - Shen 中可以做依赖类型吗?

idris - 如何创建一个只接受其他字段的字段?

scala - 从哪里开始依赖类型编程?

idris - 不能在 Idris 中使用 contrib

idris - Idris 中有理数的实现

dependent-type - 如何在 Idris 中重写函数体,以便类型对应于函数签名并且整个事物都可以编译

idris - Idris 可以支持行多态吗?

functional-programming - Idris 中依赖类型函数自动检测域

dependent-type - Idris Vect.fromList 与生成列表的用法

c++ - throw 或 delete 表达式可以依赖吗?