Zulip Chat Archive

Stream: Is there code for X?

Topic: choose an element from a fintype with positive cardinality


David Renshaw (Sep 01 2023 at 15:53):

I have this:

noncomputable def choose_element {α : Type} [DecidableEq α] [Fintype α]
    (hs : 0 < Fintype.card α) : α :=
  (truncOfCardPos hs).out

but that truncOfCardPos thing seems kind of ugly. Is there a better way?

Adam Topaz (Sep 01 2023 at 15:54):

Isn't there a Nonempty instance you can use?

Adam Topaz (Sep 01 2023 at 15:57):

E.g.

noncomputable def choose_element {α : Type} [DecidableEq α] [Fintype α]
    (hs : 0 < Fintype.card α) : α :=
  Nonempty.some <| Iff.mp Fintype.card_pos_iff hs

Adam Topaz (Sep 01 2023 at 15:57):

I don't know if that's necessarily better?

David Renshaw (Sep 01 2023 at 15:58):

yeah, that seems a bit more readable to me

Kyle Miller (Sep 01 2023 at 16:00):

There's also changing hs to Nonempty inside your proof and then using Classical.arbitrary.

I'm not suggesting making this definition, but the body is meant to simulate how it'd look in a proof.

noncomputable def choose_element {α : Type} [DecidableEq α] [Fintype α]
    (hs : 0 < Fintype.card α) : α :=
  have : Nonempty α := Fintype.card_pos_iff.mp hs -- or `rw [Fintype.card_pos_iff] at hs` in a tactic proof
  Classical.arbitrary α

Kyle Miller (Sep 01 2023 at 16:01):

There's also stuff like using the inhabit tactic to lift it to an Inhabited instance, which gives you default

noncomputable def choose_element {α : Type} [DecidableEq α] [Fintype α]
    (hs : 0 < Fintype.card α) : α := by
  rw [Fintype.card_pos_iff] at hs
  inhabit α
  exact default

Kyle Miller (Sep 01 2023 at 16:02):

(I wonder if it's out of scope for inhabit to look for hypotheses such as hs? There could be a library of @[inhabit] lemmas it consults.)

Yaël Dillies (Sep 01 2023 at 16:06):

I've said before that inhabit should match nontriviality in that it assumes the type is empty and tries to discharge the case using a finishing tactic.


Last updated: Dec 20 2023 at 11:08 UTC