Zulip Chat Archive

Stream: lean4

Topic: Numeric literals


Patrick Massot (Mar 12 2025 at 10:06):

I suspect I already asked this, but I’m not sure. Is there any way to tell Lean: “in this file, all numeric literals should be interpreted as real numbers”? This is for teaching purposes of course.

Kim Morrison (Mar 12 2025 at 10:11):

@[default_instance]
instance instOfNatReal (n : Nat) : OfNat Real n where
  ofNat := n

Kim Morrison (Mar 12 2025 at 10:11):

This at least interprets natural number literals as reals.

Kim Morrison (Mar 12 2025 at 10:12):

Presumably something similar with OfScientific works for decimals.

Kim Morrison (Mar 12 2025 at 10:13):

I'd be happy to see a command in Mathlib interpret_numeric_literals_as_reals which runs this locally.

Kyle Miller (Mar 12 2025 at 10:23):

There's a caveat to @[default_instance], which is that they can't be local, scoped, or later removed, so once you do this it's a permanent change to downstream modules.

Patrick Massot (Mar 12 2025 at 10:27):

Thanks Kim.

Patrick Massot (Mar 12 2025 at 10:28):

Indeed it works, but I wasn’t careful enough with what I wished for. I forgot I also had powers in this file. And the exponents should be natural numbers.

Patrick Massot (Mar 12 2025 at 10:28):

One sample challenge is to remove the type annotation in

example : (4 : ) = 1^3 + 1^2 - 1 + 3 := by norm_num

Patrick Massot (Mar 12 2025 at 10:30):

In this specific example I get away with a local

local macro_rules
| `($x = $y) => `(@Eq Real $x $y)

but it seems really really brittle.

Patrick Massot (Mar 12 2025 at 10:35):

The larger context is

example (x : ) (hyp : x^3 + x^2 - x + 3 = 0) : x  1 := by
  intro hx
  have H : (4 : ) = 0 :=
    calc
      4 = 1^3 + 1^2 - 1 + 3 := by norm_num
      _ = x^3 + x^2 - x + 3 := by rw [ hx]
      _ = 0 := by congr
  linarith only [H]

This is part of explaining negation and I really don’t want students to hit the error you get without the type annotation on the have line.

Patrick Massot (Mar 12 2025 at 10:48):

I tried

@[default_instance]
instance instOfNatReal (n : Nat) : OfNat Real n where
  ofNat := n

local macro_rules | `($x ^ $y:num)   => `(@HPow.hPow Real Nat Real (@instHPow.{0, 0} Real Nat (@Monoid.toNatPow.{0} Real Real.instMonoid)) $x (@OfNat.ofNat.{0} Nat $y (instOfNatNat $y))) in

example : 4 = 1^3 + 1^2 - 1 + 3 := by norm_num

but it does not work. I think the statement is the intended one, but norm_num no longer works.


Last updated: May 02 2025 at 03:31 UTC