Tactic

cas

Proves the goal by computer algebra whose steps Lean’s kernel checks: identities, derivatives, integrals, limits and bounds.

cas
proves the goal, or leaves it unchanged and says what each route tried.
cas [l₁, l₂]
the same, with l₁ and l₂ as local simp lemmas for the routes, such as a definition to unfold or an applied hypothesis.

Inside a proof, cas is the main entry point. I wanted one tactic to try on a calculation without first deciding what kind of calculation it is. You state what you want, in Mathlib’s own terms, and write cas. It tries a fixed list of routes, from determinants and ideals to derivatives, integrals and bounds on a box, and every route ends in a proof that Lean checks against your goal. If no route works, the goal stays as it was and the message tells you what was tried. That is all a refusal means: it is not a proof that the goal is false.

cas using h passes a hypothesis such as x ≠ 0 as evidence for the routes, and it has its own page. So does cas [integrate primitive := F], which checks a primitive that you supply.

Details and Options

  • cas closes the goal and proves no other statement. It does not change a goal it cannot close.
  • Identities and relations: what Mathlib’s field_simp, ring, norm_num, positivity, linarith and nlinarith prove, and real identities that the checked symbolic normalizer proves, such as sin2x+cos2x=1.
  • Calculus: deriv f x = e, HasDerivAt f e x, HasDerivWithinAt, DifferentiableAt, iteratedDeriv n f x = e for a literal n, nested derivatives, and Continuous, ContinuousOn, Differentiable, ContDiff, AnalyticAt and their relatives over ℝ.
  • Integrals: (∫ x in a..b, f x) = v and improper integrals such as (∫ t in Set.Ioi 0, f t) = v, also with their integrability, IntegrableOn f (Set.Ioi 0) ∧ ∫ t in Set.Ioi 0, f t = v, by an analytic theorem, one integration by parts or a checked primitive.
  • The theorems that the #cas modes print: algebra, matrices and number theory, limits at a rational point and at atTop and atBot, the sign of a polynomial and counts of real roots.
  • Ideals and determinants: f ∈ Ideal.span {g₁, …, gₘ} and equalities of spans, with cofactors from a Gröbner basis, and goals with determinants of matrix literals.
  • Inequalities on real variables that hypotheses bound by rational numbers, such as 0 ≤ x and x ≤ 1, by the box route of cega.
  • The routes run in a fixed order: determinants, ideals, the #cas theorems, derivatives, integrals, the checked evaluator, arithmetic, equation hypotheses, the checked identity route, the box route, elementary rewrites, norm_num, and grind last.
  • A derivative or an integral whose function needs a condition, such as x≠0 for logx, takes it from a hypothesis in the local context or from cas using h.
  • set_option cas.grindHeartbeats n sets the budget of the grind and norm_num fallbacks in thousands of heartbeats, by default 20000, and 0 turns them off.
  • set_option cas.maxDerivativeSteps n caps the goals of a proof by the derivative rules, by default 512.
  • set_option trace.cas.fallback true shows the whole diagnostics of the grind and norm_num fallbacks in the report of a failure.

Examples (24)#

Basic Examples (3)

The Pythagorean identity:

In[1]:=
example (x : ℝ) : Real.sin x ^ 2 + Real.cos x ^ 2 = 1 := by
  cas
Out[1]=

Lean accepts the proof.


A derivative, stated with Mathlib’s deriv:

In[2]:=
example (x : ℝ) : deriv Real.sin x = Real.cos x := by
  cas
Out[2]=

Lean accepts the proof.


A definite integral. cas finds an antiderivative and checks it:

In[3]:=
example : (∫ x in (0 : ℝ)..1, x * Real.exp x) = 1 := by
  cas
Out[3]=

Lean accepts the proof.

Scope (8)

An identity that needs a hypothesis. Without hx, the statement is false in Lean at x=±1:

In[4]:=
example (x : ℝ) (hx : x ^ 2 - 1 ≠ 0) :
    (x ^ 4 - 1) / (x ^ 2 - 1) = x ^ 2 + 1 := by
  cas
Out[4]=

Lean accepts the proof.


Higher derivatives, nested ones included:

In[5]:=
example (x : ℝ) :
    iteratedDeriv 3 (fun x ↦ Real.sin (2 * x)) x = -8 * Real.cos (2 * x) := by
  cas
Out[5]=

Lean accepts the proof.

In[6]:=
example (x : ℝ) (hx : 0 < x) :
    deriv (fun x ↦ deriv Real.sqrt x) x = -1 / (4 * x * Real.sqrt x) := by
  cas
Out[6]=

Lean accepts the proof.


Smoothness and analyticity:

In[7]:=
example : AnalyticAt ℝ (fun x ↦ Real.exp (Real.sin x) / (1 + x ^ 2)) 0 := by
  cas
Out[7]=

Lean accepts the proof.

In[8]:=
example : ContinuousOn (fun x ↦ Real.log x / x) (Set.Ioi 0) := by
  cas
Out[8]=

Lean accepts the proof.


Integrals with symbolic limits, and over the whole line:

In[9]:=
example (a b : ℝ) : (∫ t in a..b, Real.sin t) = Real.cos a - Real.cos b := by
  cas
Out[9]=

Lean accepts the proof.

In[10]:=
example : ∫ x : ℝ, 1 / (1 + x ^ 2) = Real.pi := by
  cas
Out[10]=

Lean accepts the proof.


Limits, written with Mathlib’s filters:

In[11]:=
open Filter Topology in
example : Tendsto (fun x : ℝ ↦ Real.sin x / x) (𝓝[≠] 0) (𝓝 1) := by
  cas
Out[11]=

Lean accepts the proof.

In[12]:=
open Filter Topology in
example : Tendsto (fun x : ℝ ↦ x * Real.exp (-x)) atTop (𝓝 0) := by
  cas
Out[12]=

Lean accepts the proof.


The sign of a polynomial, and how many real roots it has:

In[13]:=
example : ∀ x : ℝ, x ^ 4 - 4 * x + 3 ≥ 0 := by
  cas
Out[13]=

Lean accepts the proof.

In[14]:=
open Polynomial in
example : Fintype.card ((X ^ 5 - 4 * X + 2 : ℚ[X]).rootSet ℝ) = 3 := by
  cas
Out[14]=

Lean accepts the proof.


A bound on a box, from the hypotheses on x and y:

In[15]:=
example (x y : ℝ) (hx : 0 ≤ x) (hx' : x ≤ 1) (hy : 2 ≤ y) (hy' : y ≤ 3) :
    Real.exp (x * y) ≤ 21 := by
  cas
Out[15]=

Lean accepts the proof.


Matrices and polynomials over ℚ:

In[16]:=
example : (!![(1 : ℚ), 2; 3, 4])⁻¹ = !![-2, 1; 3 / 2, -1 / 2] := by
  cas
Out[16]=

Lean accepts the proof.

In[17]:=
open Polynomial in
example : gcd (X ^ 2 - 1 : ℚ[X]) (X ^ 2 - 2 * X + 1) = X - 1 := by
  cas
Out[17]=

Lean accepts the proof.

Options (2)

cas [l₁, l₂] hands lemmas to the routes. Here an applied hypothesis rewrites f (x + 1) first:

In[18]:=
example (f : ℝ → ℝ) (x : ℝ) (hf : ∀ t, f t = t ^ 2) : f (x + 1) = x ^ 2 + 2 * x + 1 := by
  cas [hf (x + 1)]
Out[18]=

Lean accepts the proof.


A definition to unfold works the same way:

In[19]:=
def shifted (t : ℝ) : ℝ := t ^ 2 + 2 * t

example (x : ℝ) : shifted (x - 1) = x ^ 2 - 1 := by
  cas [shifted]
Out[19]=

Lean accepts the proof.

Applications (2)

cas proves a bound that linarith then uses. Only the three standard axioms are used:

In[20]:=
theorem exp_lt_four (x : ℝ) (h₀ : 0 ≤ x) (h₁ : x ≤ 1) : Real.exp x < 4 := by
  have h : Real.exp x ≤ 3 := by cas
  linarith

#print axioms exp_lt_four
Out[20]=

exp_lt_four depends on the axioms propext, Classical.choice, Quot.sound.


Nicomachus’s theorem, the sum of the first n cubes:

In[21]:=
example (n : ℕ) : ∑ k ∈ Finset.range (n + 1), (k : ℝ) ^ 3 = (n * (n + 1) / 2) ^ 2 := by
  cas
Out[21]=

Lean accepts the proof.

Properties and Relations (2)

#cas prints a theorem, and cas proves the same statement in a proof:

In[22]:=
#cas [derive x] (tan x)
Out[22]=
1cos2(x)
1/cos(x)^2
Conditions
cos(x)≠0

Checked by Lean’s kernel: Derivative of the input

∀ (x : ℝ), Real.cos x ≠ 0 → HasDerivAt (fun x ↦ Real.tan x) (1 / Real.cos x ^ 2) x

from CAS.Command.hasDerivAt_of_displayRoute

The certificate: 5 checked steps
  1. Derivative of the input

    ∀ (x : ℝ), Real.cos x ≠ 0 → HasDerivAt (fun x ↦ Real.tan x) (1 / Real.cos x ^ 2) x

    Checked by Lean’s kernel · CAS.Command.hasDerivAt_of_displayRoute

  2. Partial derivative in x: indexed rules compute Expr.diff

    (CAS.Verified.Expr.DiffDerivation.build 0 (𝕏[0].sin.div 𝕏[0].cos)).rawDerivative =
      CAS.Verified.Expr.diff 0 (𝕏[0].sin.div 𝕏[0].cos)

    Checked by Lean’s kernel · CAS.Verified.Expr.DiffDerivation.rawDerivative_eq_diff

  3. Partial derivative in x: normalization preserves evaluation

    ∀ (ρ : Fin 1 → ℝ),
      CAS.Verified.Expr.eval ρ
          (CAS.Verified.Expr.DiffDerivation.build 0 (𝕏[0].sin.div 𝕏[0].cos)).simplifiedDerivative =
        CAS.Verified.Expr.eval ρ (CAS.Verified.Expr.DiffDerivation.build 0 (𝕏[0].sin.div 𝕏[0].cos)).rawDerivative

    Checked by Lean’s kernel · CAS.Verified.Expr.DiffDerivation.eval_simplifiedDerivative_eq_rawDerivative

  4. Partial derivative in x: side-conditioned display normalization

    ∀ (ρ : Fin 1 → ℝ),
      CAS.Verified.Expr.Alg.SideHolds ρ
          (CAS.Command.displayDerivativeRoute
              (CAS.Verified.Expr.DiffDerivation.build 0 (𝕏[0].sin.div 𝕏[0].cos))).nonzero →
        CAS.Verified.Expr.eval ρ
            (CAS.Command.displayDerivativeRoute
                (CAS.Verified.Expr.DiffDerivation.build 0 (𝕏[0].sin.div 𝕏[0].cos))).rhs =
          CAS.Verified.Expr.eval ρ
            (CAS.Verified.Expr.DiffDerivation.build 0 (𝕏[0].sin.div 𝕏[0].cos)).simplifiedDerivative

    Checked by Lean’s kernel · CAS.Command.displayDerivativeRoute_sound

  5. Partial derivative in x: analytic semantics of the displayed result

    ∀ (x : ℝ^1),
      CAS.Verified.Expr.ValidAt x.ofLp (𝕏[0].sin.div 𝕏[0].cos) →
        CAS.Verified.Expr.Alg.SideHolds x.ofLp
            (CAS.Command.displayDerivativeRoute
                (CAS.Verified.Expr.DiffDerivation.build 0 (𝕏[0].sin.div 𝕏[0].cos))).nonzero →
          (fderiv ℝ (fun y ↦ CAS.Verified.Expr.eval y.ofLp (𝕏[0].sin.div 𝕏[0].cos)) x) (EuclideanSpace.single 0 1) =
            CAS.Verified.Expr.eval x.ofLp
              (CAS.Command.displayDerivativeRoute
                  (CAS.Verified.Expr.DiffDerivation.build 0 (𝕏[0].sin.div 𝕏[0].cos))).rhs

    Checked by Lean’s kernel · CAS.Command.fderiv_apply_single_eq_eval_displayDerivative

The computation
  • Variables: x
  • Analytic domain conditions

    Raw checked nonzero requirements: cos(x)
    Raw checked positivity requirements: (none)
  • Partial derivative in x

    • 1. Apply symbolic differentiation rules

      raw result: (cos(x)*1*cos(x) - sin(x)*-sin(x)*1)/cos(x)^2
    • 2. Normalize the symbolic derivative unconditionally

      normalized result: 1/cos(x)^2
    • 3. Apply checked side-conditioned cleanup

      displayed result: 1/cos(x)^2
      additional nonzero requirements: (none)
In[23]:=
example (x : ℝ) (h : Real.cos x ≠ 0) :
    HasDerivAt (fun x ↦ Real.tan x) (1 / Real.cos x ^ 2) x := by
  cas
Out[23]=

Lean accepts the proof.


cas? runs the same routes and tells you the call to keep in your proof:

In[24]:=
example (x : ℝ) (h₀ : 0 ≤ x) (h₁ : x ≤ 1) : Real.exp x ≤ 3 := by
  cas?
Out[24]=

Try this

cega

Lean checked the suggested replacement against the original goal. Selected route: CAS route: checked CEGA box enclosure of an ordinary inequality.

Possible Issues (4)

A false statement is refused. The message lists what each route tried, and it does not prove that the goal is false:

In[25]:=
example (x : ℝ) : Real.sin x ^ 2 + Real.cos x ^ 2 = 2 := by
  cas
Out[25]=

Error

cas could not prove this arithmetic relation. The statement may be false, or it may lie outside the supported normalization and arithmetic fragment
The rest of the message
Polynomial equation route:
  `grind` failed
  case grind
  x : ℝ
  h : ¬Real.sin x ^ 2 + Real.cos x ^ 2 = 2
  ⊢ False
  [grind] Goal diagnostics
    [facts] Asserted facts
      [prop] ¬Real.sin x ^ 2 + Real.cos x ^ 2 = 2
    [eqc] False propositions
      [prop] Real.sin x ^ 2 + Real.cos x ^ 2 = 2
    [eqc] Equivalence classes
      [eqc] {1, (Real.sin x ^ 2 + Real.cos x ^ 2 - 2) * (Real.sin x ^ 2 + Real.cos x ^ 2 - 2)⁻¹}
    [ematch] E-matching patterns
      [thm] Nat.pow_pos: [@HPow.hPow `[ℕ] `[ℕ] `[ℕ] `[instHPow] #2 #1]
      [thm] Nat.div_pow_of_pos: [@HPow.hPow `[ℕ] `[ℕ] `[ℕ] `[instHPow] #2 #1]
    [ring] Ring `ℝ`
      [basis] Basis
        [_] Real.sin x ^ 2 * (Real.sin x ^ 2 + Real.cos x ^ 2 - 2)⁻¹ +
                    Real.cos x ^ 2 * (Real.sin x ^ 2 + Real.cos x ^ 2 - 2)⁻¹ +
                  -2 * (Real.sin x ^ 2 + Real.cos x ^ 2 - 2)⁻¹ +
                -1 =
              0
    [limits] Thresholds reached
      [limit] maximum number of E-matching rounds has been reached, threshold: `(ematch := 0)`
      [limit] maximum number of case-splits has been reached, threshold: `(splits := 0)`
Checked identity route:
  cas could not identify the two sides: the checked normalizer does not reduce their difference to zero.
  Normalized difference:
    CAS.Verified.Expr.int (-1)
  canonical form route: the canonical rational form of the difference is not zero.
  Canonical difference:
    ((𝕏[0].sin.pow 2).add (𝕏[0].cos.pow 2)).sub (CAS.Verified.Expr.nat 2)
Elementary rewrite route:
  no elementary rewrite applies
Grind fallback:
  `grind` failed (`set_option trace.cas.fallback true` shows its diagnostics)

A wrong derivative. #cas [derive x] (x ^ 2) prints the one that is right:

In[26]:=
example (x : ℝ) : deriv (fun x ↦ x ^ 2) x = 3 * x := by
  cas
Out[26]=

Error

cas computed a checked derivative, but it does not match the stated result. Check the claimed derivative, or run the corresponding `#cas [derive]` command to inspect the normalized result.
The rest of the message
Remaining conversion goals:
  x = 0
Checked normalizer route:
  cas could not identify the two sides: the checked normalizer does not reduce their difference to zero.
  Normalized difference:
    𝕏[0].neg
  canonical form route: the canonical rational form of the difference is not zero.
  Canonical difference:
    𝕏[0].neg

cas has no modes. The words of #cas, such as derive and integrate, are not lemmas:

In[27]:=
example (x : ℝ) : deriv Real.sin x = Real.cos x := by
  cas [derive]
Out[27]=

Error

Unknown identifier `derive`

The box route needs rational bounds on every variable. For all real x, this one is Mathlib’s Real.add_one_le_exp:

In[28]:=
example (x : ℝ) : Real.exp x ≥ x + 1 := by
  cas
Out[28]=

Error

cas could not prove this arithmetic relation. The statement may be false, or it may lie outside the supported normalization and arithmetic fragment
Box enclosure route:
  cas box route: no rational bounds on `x` in the hypotheses; the route needs hypotheses `a ≤ x` and `x ≤ b`, `x ∈ Set.Icc a b`, or `|x| ≤ r` with rational literal endpoints
Command theorem route:
  cas: the expression is not a polynomial with rational coefficients
Grind fallback:
  `grind` failed (`set_option trace.cas.fallback true` shows its diagnostics)

Neat Examples (3)

A power of 2 with a 27 digit exponent, modulo a prime:

In[29]:=
example : (2 : ℕ) ^ 123456789123456789123456789 % 1000000007 = 612059118 := by
  cas
Out[29]=

Lean accepts the proof.


You can teach cas a derivative. Here is a function it cannot read, the integral of a Gaussian from 0 to x, with the fundamental theorem of calculus registered as a rule:

In[30]:=
noncomputable def gaussInt (x : ℝ) : ℝ := ∫ t in (0 : ℝ)..x, Real.exp (-t ^ 2)

theorem hasDerivAt_gaussInt (x : ℝ) : HasDerivAt gaussInt (Real.exp (-x ^ 2)) x :=
  (Continuous.integral_hasStrictDerivAt (by fun_prop) 0 x).hasDerivAt

attribute [cas_deriv] hasDerivAt_gaussInt
Out[30]=

Lean accepts the proof.

Now cas applies the rule together with the chain rule:

In[31]:=
example (x : ℝ) : deriv (fun x ↦ gaussInt (x ^ 2)) x = 2 * x * Real.exp (-x ^ 4) := by
  cas
Out[31]=

Lean accepts the proof.


A product that telescopes:

In[32]:=
example : ∀ n : ℕ, ∏ k ∈ Finset.Icc 1 n, ((k : ℝ) + 1) / k = n + 1 := by
  cas
Out[32]=

Lean accepts the proof.

See Also

cas using · cas? · cas [integrate primitive := F] · cas_nf · cega · derive · integrate · limit