natToFin when there is evidence that the conversion will work

*爱你&永不变心* 提交于 2019-12-07 05:45:20

问题


The natToFin function from the standard library has the following signature:

natToFin : Nat -> (n : Nat) -> Maybe (Fin n)

natToFin 4 5 returns Just (FS (FS (FS (FS FZ)))) : Maybe (Fin 5), while natToFin 5 5 returns Nothing.

I would like a function with the following signature:

myNatToFin : (m : Nat) -> (n : Nat) -> { auto p : n `GT` m } -> Fin n

It behaves the same as the standard lib function but doesn't need to return a Maybe because it is always possible to generate a Fin n from m given that n is greater than m.

How do I implement myNatToFin?


回答1:


You can do it directly by recursing on m, n, and the evidence for n `GT` m at the same time:

import Data.Fin

myNatToFin : (m : Nat) -> (n : Nat) -> {auto p : n `GT` m} -> Fin n
myNatToFin Z (S n) = FZ
myNatToFin (S m) (S n) {p = LTESucc _} = FS $ myNatToFin m n

Note that you need to pattern match on p in the second case (even though its value is not used on the right-hand side) so that the automatic argument for the recursive call can be filled in.



来源:https://stackoverflow.com/questions/29908731/nattofin-when-there-is-evidence-that-the-conversion-will-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!