1

I am very new to Coq, and hope my question is not too basic. I am simply wondering how I define dependent functions in Coq. For example, how could I define a function from Booleans that sends true to true and false to the natural number seven ? I assume one can use the usual (f x) notation to apply a dependent function f to an input x.

1 Answers1

3

To define dependent functions in Coq, you refer back to the parameter when specifying the type. In your example, you take a Boolean, let's call it b, and your return type is match b with true => bool | false => nat end (or if b then bool else nat).

In code, that looks like the following:

Definition foo (b : bool)
  : match b with true => bool | false => nat end
  := match b with true => true | false => 7 end.

Compute foo true. (* = true *)
Compute foo false. (* = 7 *)

There is a little bit of magic that goes on in figuring out the type of the match construct here, if you give more type annotations it looks like

Definition foo'
  : forall b : bool, match b return Set with true => bool | false => nat end
  := fun b : bool =>
     match b as b'
     return match b' return Set with true => bool | false => nat end
     with true => true | false => 7 end.

Here, since the match construct can have different types depending on the value of b (which can be an arbitrary term, not just a variable), we use the annotation as b' return ... to give b a new name, and then specify the type of the match depending on the value of b'.

However, particularly when matching on a variable, Coq can often figure out the return ... annotation on it's own.

You can find some documentation of the match construct here, in the reference manual

Jasper Hugunin
  • 486
  • 2
  • 8
  • Thanks. I tried to use the same idea to define a polymorphic identity function as – Richard Southwell Nov 03 '20 at 18:49
  • Definition other_id (t : Type) : t -> t := (fun a => a). Compute (other_id nat 7). – Richard Southwell Nov 03 '20 at 18:50
  • But I was surprised that only other_id 7 worked (my function expected one less input than I was expecting) – Richard Southwell Nov 03 '20 at 18:51
  • 1
    That would be worth another question, but it probably has something to do with [implicit arguments](https://coq.inria.fr/refman/language/extensions/implicit-arguments.html). Your intuition is correct for the plain version of the language; there is then some sugar added on top to make things easier to use. – Jasper Hugunin Nov 03 '20 at 23:23
  • Thanks for informing me. I wish I could turn that sugar off. – Richard Southwell Nov 04 '20 at 08:10
  • Most of the sugar can be turned off, but how to do it is sometimes buried in hard-to-find options. If you want to have a longer discussion, Coq users and developers are using [Zulip](https://coq.zulipchat.com/) as a chat room; I'm on there pretty often myself. It's nice for a bit more open ended questions than StackOverflow. – Jasper Hugunin Nov 05 '20 at 04:34