Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix incomplete pattern matching in agda

Here's the code from a custom agda library. In the following code, ๐• stands for vector and โ„• for Natural numbers. The take๐• type is similar to that of Haskell. Example: "take 3 [1,2,3,4,5,6,7,8]" results in [1,2,3].

take๐• : โˆ€{A : Set}{n : โ„•} โ†’ (m : โ„•) โ†’ ๐• A n โ†’ ๐• A m
take๐• 0 xs = []
take๐• (suc m) (x :: xs) = x :: take๐• m xs

I keep getting the error:

Incomplete pattern matching for take๐•. Missing cases:
take๐• (suc m) [] when checking the definition of take๐•

I dont understand, what possible proof I might be missing out.

like image 604
centrinok Avatar asked Nov 21 '25 03:11

centrinok


2 Answers

The type signature of take๐• says that for any completely unconstrained m you can return a Vec of length m having a Vec of length n. This is not true of course as m must be less or equal to n, because you want to return a prefix of a Vec. And since a number of elements to take and the length of a Vec are unrelated to each other, Agda gives you that error about incomplete pattern matching.

In Agda standard library the restriction that m is less or equal to the length of an input Vec is expressed as follows:

take : โˆ€ {a} {A : Set a} m {n} โ†’ Vec A (m + n) โ†’ Vec A m

You can also define something like

take : โˆ€ {a} {A : Set a} {m n} โ†’ m โ‰ค n โ†’ Vec A n โ†’ Vec A m

Or even

take : โˆ€ {a} {A : Set a} m {n} โ†’ Vec A n โ†’ Vec A (m โŠ” n)

to model the behavior of Data.List.take (where _โŠ”_ means min in Agda stdlib).

like image 133
user3237465 Avatar answered Nov 24 '25 06:11

user3237465


You are pattern-matching on m and a vector xs of type ๐• A n. There is no guarantee that, because m is suc-headed that xs is non-empty. As the error suggests, you need to also consider the case where m is a suc and xs is empty.

Alternatively, you can write a function with a more precise type guaranteeing the fact that xs is at least as long as m. This is what is used in the standard library:

take : โˆ€ {A : Set} m {n} โ†’ Vec A (m + n) โ†’ Vec A m
like image 38
gallais Avatar answered Nov 24 '25 07:11

gallais