Zulip Chat Archive

Stream: lean4

Topic: Get `Expr` from arbitrary definition?


Vasilii Nesterov (Jul 02 2024 at 11:08):

Hello! Is it possible in Lean to obtain the Expr object from an arbitrary let definition? I see that there is a ToExpr class for this purpose, but it works only with a small set of types.

Jovan Gerbscheid (Jul 02 2024 at 11:18):

Are you looking for something like the Qq library? I allows you to make an Expr object like this:

import Qq
open Qq
/-
Lean.Expr.app
  (Lean.Expr.app
    (Lean.Expr.app
      (Lean.Expr.app
        (Lean.Expr.app
          (Lean.Expr.app
            (Lean.Expr.const `HAdd.hAdd [Lean.Level.zero, Lean.Level.zero, Lean.Level.zero])
            (Lean.Expr.const `Nat []))
          (Lean.Expr.const `Nat []))
        (Lean.Expr.const `Nat []))
      (Lean.Expr.app
        (Lean.Expr.app (Lean.Expr.const `instHAdd [Lean.Level.zero]) (Lean.Expr.const `Nat []))
        (Lean.Expr.const `instAddNat [])))
    (Lean.Expr.app
      (Lean.Expr.app
        (Lean.Expr.app (Lean.Expr.const `OfNat.ofNat [Lean.Level.zero]) (Lean.Expr.const `Nat []))
        (Lean.Expr.lit (Lean.Literal.natVal 1)))
      (Lean.Expr.app (Lean.Expr.const `instOfNatNat []) (Lean.Expr.lit (Lean.Literal.natVal 1)))))
  (Lean.Expr.app
    (Lean.Expr.app
      (Lean.Expr.app (Lean.Expr.const `OfNat.ofNat [Lean.Level.zero]) (Lean.Expr.const `Nat []))
      (Lean.Expr.lit (Lean.Literal.natVal 1)))
    (Lean.Expr.app (Lean.Expr.const `instOfNatNat []) (Lean.Expr.lit (Lean.Literal.natVal 1))))

-/
#eval q(1+1)

Vasilii Nesterov (Jul 02 2024 at 11:42):

Thanks, that's almost what I was looking for! Can I use it with local definitions? Something like this:

def foo : Expr :=
  let n :  := 1 + 1
  q(n)

Eric Wieser (Jul 02 2024 at 11:45):

You can do

def foo : Expr :=
  let n : Q() := q(1 + 1)
  q($n)

Last updated: May 02 2025 at 03:31 UTC