Zulip Chat Archive

Stream: Is there code for X?

Topic: Getting the first element of a nonempty list


Anne Baanen (Jun 07 2021 at 09:11):

I have a list xs and an element x ∈ xs. What is the best way to get the first element of xs: create a local inhabited instance and use docs#list.head, use docs#list.head' and prove it returns some, or something else?

Anne Baanen (Jun 07 2021 at 09:13):

In other words, does the following already exist:

def list.head_of_mem {α : Type*} : Π (xs : list α) {x : α} (h : x  xs), α
| (y :: _) _ _ := y

Pontus Sundqvist (Jun 07 2021 at 11:19):

You can use list.exists_cons_of_ne_nil to get it.

theorem get_head (x : ) (l : list ) (hx : x  l) :
   (b : ) (L : list ), l = b :: L :=
list.exists_cons_of_ne_nil (list.ne_nil_of_mem hx)

Anne Baanen (Jun 07 2021 at 11:22):

Unfortunately, that would make the definition noncomputable. :(

Ruben Van de Velde (Jun 07 2021 at 11:37):

Oddly, list.last does exist in that shape

Yakov Pechersky (Jun 07 2021 at 13:02):

I use list.nth_le 0 (length_pos proof based on the fact that there is an element in it)


Last updated: Dec 20 2023 at 11:08 UTC