将Nat保持在固定范围内

时间:2015-03-14 17:37:45

标签: idris

我希望Nat保持在固定范围内。我希望函数incrdecr如果要将数字推到范围之外就会失败。这似乎可能是Fin的一个很好的用例,但我不确定如何使其工作。类型签名可能如下所示:

- Returns the next value in the ordered finite set.
- Returns Nothing if the input element is the last element in the set. 
incr : Fin n -> Maybe (Fin n)

- Returns the previous value in the ordered finite set.
- Returns Nothing if the input element is the first element in the set.
decr : Fin n -> Maybe (Fin n)

Nat将用于索引Vect n。如何实施incrdecrFin甚至是正确的选择吗?

1 个答案:

答案 0 :(得分:3)

我想最简单的方法是使用Data.Fin中的一些标准Fin↔Nat转换函数:

incr, decr : {n : Nat} -> Fin n -> Maybe (Fin n)
incr {n=n} f = natToFin (succ $ finToNat f) n

decr {n=n} f = case finToNat f of
    Z => Nothing
    S k => natToFin k n
相关问题