Zulip Chat Archive

Stream: new members

Topic: What is \u?


Albert Jiang (Mar 31 2022 at 17:32):

Absolute beginner question, but what is the \u operator on natural numbers? Thanks!

Albert Jiang (Mar 31 2022 at 17:32):

Somehow searching the documentation gives very little results maybe due to the operator search feature...

Jireh Loreaux (Mar 31 2022 at 17:34):

Do you mean ? This is coe. It is a coercion. In this case, it's the natural map ℕ → ℤ.

Jireh Loreaux (Mar 31 2022 at 17:35):

Note, coercions can exist between lots of different types, so is not always this map (it depends on the source and target types).

Albert Jiang (Mar 31 2022 at 17:35):

Ah I see! Thank you! So it just converts the type of the operand in the most intuitive way?

Jireh Loreaux (Mar 31 2022 at 17:36):

sorry, I implicitly assumed the output type was ℤ, but you didn't say that, so what you are looking at may even be a different coercion.

Albert Jiang (Mar 31 2022 at 17:37):

Oh so it does convert the type depending on the type expected. Awesome!

Albert Jiang (Mar 31 2022 at 17:37):

Thanks!

Jireh Loreaux (Mar 31 2022 at 17:37):

It can't convert any type to any other type, it only works for for types with a coercion defined.

Albert Jiang (Mar 31 2022 at 17:37):

I'm looking at a case from nat to int :)

Jireh Loreaux (Mar 31 2022 at 17:37):

You need a has_coe_t (or has_coe) instance between the types. docs#has_coe_t

Jireh Loreaux (Mar 31 2022 at 17:40):

If you look at the docs for that and then click the "instances" arrow, you'll see the list of coercions. For example, you'll see nat.cast_coe which actually gives a coercion from to any type α with a zero, a one, and addition.

Kyle Miller (Mar 31 2022 at 17:41):

One neat thing is that Lean will insert coercions for you when types don't match up:

def foo (x : ) :  := x

#print foo
/-
def foo : ℕ → ℤ :=
λ (x : ℕ), ↑x
-/

This occurs while the elaborator is trying to take your expression and fill out all the missing details before it hands it off to the kernel for a final check.

Kyle Miller (Mar 31 2022 at 17:42):

You can turn this feature off:

set_option elaborator.coercions false

def foo (x : ) :  := x
/-
type mismatch, term
  x
has type

but is expected to have type

-/

Kyle Miller (Mar 31 2022 at 17:44):

Here's a way you can experimentally check what the coercion is from within Lean:

example (n : ) : false :=
begin
  set m :  := n with h,
  unfold_coes at h,
  /-
  n : ℕ,
  m : ℤ := ↑n,
  h : m = int.of_nat n
  ⊢ false
  -/
end

Kyle Miller (Mar 31 2022 at 17:45):

I guess the constructor docs#int.of_nat takes priority over docs#nat.cast_coe. The coercion is defined right here: https://github.com/leanprover-community/lean/blob/master/library/init/data/int/basic.lean#L21

Jireh Loreaux (Mar 31 2022 at 17:48):

Also, if you are using VS Code, in the widget panel you can click on the ↑ in the tactic state to see which coercion is being used.


Last updated: Dec 20 2023 at 11:08 UTC