How can I match on a specific value in Coq?

时光总嘲笑我的痴心妄想 提交于 2019-12-13 03:50:23

问题


I'm trying to implement a function that simply counts the number of occurrences of some nat in a bag (just a synonym for a list).

This is what I want to do, but it doesn't work:

Require Import Coq.Lists.List.
Import ListNotations.

Definition bag := list nat.

Fixpoint count (v:nat) (s:bag) : nat :=
  match s with
  | nil    => O
  | v :: t => S (count v t) 
  | _ :: t => count v t
  end. 

Coq says that the final clause is redundant, i.e., it just treats v as a name for the head instead of the specific v that is passed to the call of count. Is there any way to pattern match on values passed as function arguments? If not, how should I instead write the function?

I got this to work:

Fixpoint count (v:nat) (s:bag) : nat :=
match s with
| nil    => O
| h :: t => if (beq_nat v h) then S (count v t) else count v t
end. 

But I don't like it. I'd rather pattern match if possible.


回答1:


Pattern matching is a different construction from equality, meant to discriminate data encoded in form of "inductives", as standard in functional programming.

In particular, pattern matching falls short in many cases, such as when you need potentially infinite patterns.

That being said, a more sensible type for count is the one available in the math-comp library:

count : forall T : Type, pred T -> seq T -> nat
Fixpoint count s := if s is x :: s' then a x + count s' else 0.

You can then build your function as count (pred1 x) where pred1 : forall T : eqType, T -> pred T , that is to say, the unary equality predicate for a fixed element of a type with decidable (computable) equality; pred1 x y <-> x = y.




回答2:


I found in another exercise that it's OK to open up a match clause on the output of a function. In that case, it was "evenb" from "Basics". In this case, try "eqb".



来源:https://stackoverflow.com/questions/46383547/how-can-i-match-on-a-specific-value-in-coq

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