Lean 4.0
github.com> Lean is a new open source theorem prover being developed at Microsoft Research. It is a research project that aims to bridge the gap between interactive and automated theorem proving. Lean can be also used as a programming language. Actually, some Lean features are implemented in Lean itself.
I've heard of Lean some time ago and is now v4. Is the opensource part which is new or has this text not been updated since v1?
I have trouble parsing your sentence, so hopefully what follows will help.
- Lean has always been open source.
- Lean 4 has been in development for a while, with the first milestone (alpha version) published in January 2021.
LeanDojo shows promise in allowing interaction with the proof environment programmatically and through LLMs: https://leandojo.org/.
This NY Times article is a nice overview of AI in math proofs: https://www.nytimes.com/2023/07/02/science/ai-mathematics-ma... (https://archive.ph/t0BhD)
Here is a chart of Mathlib's growth: https://leanprover-community.github.io/mathlib_stats.html
LeanDojo looks cool! I will check it out. I did the natural number game in lean 3, and was excited to see the author of "How to Prove it" had written an online book, "How to prove it with Lean" to as an accompaniment to the book, but it was written in lean 4. I decided to redo it in Lean 4 (still working on it) and had some troubles but was super happy with the responses I got on the Zulip Chat. It was a bit tricky to install it but the lake system seems like a big improvement over how I installed lean 3. I used the emacs version of lean mode for lean 4.
How to Prove it with lean https://djvelleman.github.io/HTPIwL/ Lean 4 Natural Number Game https://adam.math.hhu.de/#/g/hhu-adam/NNG4 Lean Zulip Chat https://leanprover.zulipchat.com/ Emacs lean 4 mode https://github.com/leanprover/lean4-mode
Exciting! I've been picking up some small side projects in Lean again to add more to https://agentultra.github.io/lean-4-hackers/ -- a guide for programmers interested in using it as a programming language.
Congrats on the milestone!
That's an excellent starting guide, nice!
One of my major concerns with Lean 4 is when I asked about mathlib compatibility some 2-3 years ago and the only reply I got was from Kevin Buzzard, implying that the best we can do is essentially rewrite it all!
Correct me if I am wrong, but I think mathlib still uses a community-maintained fork of Lean 3. I love Lean and its relative ease-of-use compared to e.g. Coq, but man, having to rewrite all of mathlib is a real bummer if that is indeed what has to happen for Lean 4 compatibility.
Mathlib was fully ported to Lean 4 (https://github.com/leanprover-community/mathlib4), and the Lean 3 version is deprecated now.
Edit: Adding a little bit more detail, it was ported one file at a time, using the automated translation from mathport (https://github.com/leanprover-community/mathport) as a starting point.
The Lean Zulip chat includes a "Is there code for X" section; you can go there and ask if a specific theorem or research problem has been formalized/verified in Lean, and if not, whether someone is working or intends to work on it. This way you can form impromptu working groups if you find others interested in your problem.
I'm a programmer and I'm excited to learn Lean as a new tool for thought. I find that Haskell sells itself as a programming language but the reality is quite arcane, and its tools feel slow and bloated. Lean 4 is sort of the opposite, selling itself as a math toolkit but actually having very considerately (and practically) designed support tools (VSCode integration, build system) and core language features. I'm reading through Functional Programming in Lean now, supplementing with the Lean Manual and also Lean's prelude file, which is well commented and pretty readable. I love that the output window's contents are clickable ("failed to synthesize type class X Y Z" -> click on X, Y or Z to go to the definitions). I'm excited to try out the widget interface, which lets you complete proofs through visuospatial reasoning (see the Rubix cube project). I'm really hoping that this serves as a new tool for programming-minded people to learn math and contribute easy-to-understand proofs in a way that was never possible before. Once I've gone through the beginner materials, I want to try the math problems at the beginning of https://brickisland.net/DDGSpring2023/, which has great tools for its programming projects but nothing for its proof assignments.
The documentation still has holes, but the Lean community is more helpful and welcoming than any other I've ever encountered, and I'm confident that I'll get an answer for every question I have.
For the Lean folks: an entry on learnxinyminutes is an absolute must in my book. It would be a great place to demonstrate how familiar and practical Lean can be, with its for loops and arrays and hash maps and whatever else. Generally if a language is not there, I figure it must not be mature enough to try out (Lean has been an exception for me).
Reading some of the other comments that say that Functional Programming in Lean is a good enough introduction and a learnxinyminutes is unnecessary, I feel I need to clarify that y should be somewhere between 5 and 15. Functional Programming in Lean is going to be probably 20 hours or more for me.
There is no excuse anymore. I have to try it out.
Me too, I want to follow
https://github.com/blanchette/logical_verification_2023
The hitchhiker's guide
I tried Lean twice and what caused me to stop both times was a severe lack of documentation. That's a shame, because it's an awesome language.
Get on Zulip[1] and ask for help when stuck. The community is friendly and has gotten quite large although they are mostly mathematicians at the moment.
I also tried to get into it recently, and I feel theorem proving has been pretty substantially oversold. It seems that if you wanted to work through the proofs in even an advanced undergraduate or early graduate textbook, you would basically have publishable material at the end because of the lack of cohesive libraries. There is a lot that gets buried in and is still open to implementation details, and I don't see any clear way of simply proceeding. It started to feel like a major distraction from just doing the mathematics rather than an aid, like it's supposed to be. It feels a little like the Rust ecosystem, where there is a land grab rush to introduce various libraries.
I agree that there's generally too little results in mathlib and for that matter in any theorem prover, but I didn't think that work on formalizing such stuff (advanced undergrad results / early grad results) is publishable. Was I wrong in this?
There's plenty of published papers about newly formalized proofs, even in "undergrad" math. A formal proof development generally brings to light new information about the original proof, both by plugging all potential inaccuracies/missing steps and in being especially easy to refactor, abstracting out common patterns that might be reused elsewhere.
Kinda agree but Mathlib and its documentation makes for a big corpus to learn by example from. Not ideal but it helps.
A https://learnxinyminutes.com/ for Lean and Lean Mathlib would be a helpful resource
On the contrary, I think the basics are covered pretty well by the official documentation, but it's lacking the more advanced stuff.
I agree; for simple and "beginning intermediate" tasks, Functional Programming in Lean has it all; but the more advanced features are only documented in the source code and doc-strings. There is also a lack of general listings: for data structures, for file access API, for algorithms etc.
Is there an eBNF+PEG or similar grammar for the language parser that a more complete language reference can be generated from?
Does Lean have docstrings with embedded markup like Python?
The Python Language Reference: https://docs.python.org/3/reference/
The Python Language Reference > 10. Full Grammar specification: https://docs.python.org/3/reference/grammar.html
LearnXinYminutes > Where X=Python: https://learnxinyminutes.com/docs/python/
In the language and then the docs, Python's collections.abc Abstract Base Classes did not initially exist. There's now a table of ABCs in the docs: https://docs.python.org/3/library/collections.abc.html#colle...
In Python, they're not interfaces, they're ABCs.
Same, I also found no good "for programmers" introduction.
There is a short one[1] from Functional Programming in Lean, which is itself an introduction to Lean 4 from the programming's perspective. Highly recommended if you're interested in dependent types.
[1]: https://leanprover.github.io/functional_programming_in_lean/...
I'm not looking to use it as a programming language, but I'd like to see an introduction to theorem proving using Lean that is more explicit in its explanation of semantics than the ones that assume an existing math background
Theorem Proving in Lean 4: https://leanprover.github.io/theorem_proving_in_lean4/
I only had a basic knowledge of first-order logic and set theory before reading TPiL4. It wasn't easy, but now I can prove theorems in Lean. By the way, I still can't write a program in any language.
Because the audience isn't "programmers".
I don’t think that your post is hostile. But from what I’ve heard, it is untrue because Lean 4 is intended to be a general purpose programming language, not only a theorem prover. I can’t find a source that directly states this goal but at the least this paper by Leo de Moura and Sebastian Ullrich presents it as a programming language:
https://link.springer.com/chapter/10.1007/978-3-030-79876-5_...
Microsoft also sponsored David Thrane Christiansen’s book, Functional Programming in Lean[1] (which I’m sure you know about!). That is another indication that they intend to reach programmers.
[1] https://leanprover.github.io/functional_programming_in_lean/
It seems general programming is more in focus now, but for context, the "Programming in Lean" book was only completed recently as compared to the multiple theorem proving documents which have been around for a while. The Christiansen book looks worth waiting for though and I really hope Lean can gain popularity as a general purpose language.
How can the audience of a general-purpose programming language not be "programmers"?
I think that is unnecessarily hostile; I believe Lean 4 can become a very capable programming language for mundane tasks!
Hostile? I just stated that the audience isn't programmers.
The age of guilds has long passed
Are people like these not programmers? https://leandojo.org/
I really find how theoreticians approach things to be challenging. Given that I headed to rosetta code to find some examples. Here's FizzBuzz in Lean 4:
https://rosettacode.org/wiki/FizzBuzz#Lean
def fizz : String :=
"Fizz"
def buzz : String :=
"Buzz"
def newLine : String :=
"\n"
def isDivisibleBy (n : Nat) (m : Nat) : Bool :=
match m with
| 0 => false
| (k + 1) => (n % (k + 1)) = 0
def getTerm (n : Nat) : String :=
if (isDivisibleBy n 15) then (fizz ++ buzz)
else if (isDivisibleBy n 3) then fizz
else if (isDivisibleBy n 5) then buzz
else toString (n)
def range (a : Nat) (b : Nat) : List (Nat) :=
match b with
| 0 => []
| m + 1 => a :: (range (a + 1) m)
def getTerms (n : Nat) : List (String) :=
(range 1 n).map (getTerm)
def addNewLine (accum : String) (elem : String) : String :=
accum ++ elem ++ newLine
def fizzBuzz : String :=
(getTerms 100).foldl (addNewLine) ("")
def main : IO Unit :=
IO.println (fizzBuzz)
#eval main
Hopefully that's helpful to others.Whoever wrote this was probably trying to showcase more of the language's functional features (or just trying to be clever). This works:
You can run it with `lean --run FizzBuzz.lean`, and you can read more about programming in Lean 4 at https://leanprover.github.io/functional_programming_in_lean/.def main := for i in [1:101] do if i % 15 == 0 then IO.println "FizzBuzz" else if i % 3 == 0 then IO.println "Fizz" else if i % 5 == 0 then IO.println "Buzz" else IO.println s!"{i}"Thanks. I appreciate it. According to
That's about 1,000 pages. Some of us who are less ambitious and motivated need an under 5-minutes example to feel compelled to engage with such a large amount of documentation. Essentially the problem is "There's hundreds of programming languages I'll never have the time to learn. Show me why I should care about this one and do it quickly."$ find leanprover.github.io/functional_programming_in_lean -name \*.html -exec html2text {} \; | wc -w 271248Given that, I actually appreciate the fancy example. It really shows off some interesting features in reaching a goal that's really simple to understand.
It looks similar to Haskell in that it approaches programming in a mathematically formal and rigorous way.
If you're deeply involved in the project, an example that would be really exciting to me would be a lean version of one of these proofs: https://en.wikipedia.org/wiki/Category:Computer-assisted_pro... or https://en.wikipedia.org/wiki/Computer-assisted_proof#Theore...
Start the example with how the proof was initially tackled on a computer and show the challenges faced and then demonstrate how lean can do it more elegantly.
I appreciate your time.
None of these proofs listed in the Wikipedia page are formalized in Lean at the moment, although a few are formalized in other theorem provers (Four Color Theorem in Coq, Kepler Conjecture in Isabelle). The "Formalization papers using Lean" section of https://leanprover-community.github.io/papers.html lists some theorems whose proofs have been verified in Lean, but (despite being written in Isabelle) I think the Kepler Conjecture formalization is the best example of what you have in mind.
The main difference between most of the examples you list via the Wikipedia page and the examples listed in the URL I cited above is how the computer is being used: in many cases, "computer-assisted" means an ad-hoc program was used to check a bunch of cases which would be too tedious for a human to check. But what happens if there is a bug in the used ad-hoc program (or, e.g., in a linear programming solver)? To increase confidence in the verification result, ideally both the validity of the case-checking and the logic for deducing the main theorem from the checked cases would be verified by a small and general "kernel"/proof checker. This is what theorem provers such as Lean, Coq and Isabelle allow.
I do not see how you are getting 1000 pages; the pdf is about 400 pages with copious amounts of sparse code blocks, and the introductory stuff (The chapters Getting to know Lean and Hello World) run about 86 pages. Certainly not "Lean in 5 minutes" for sure, but not a spellbook either.
In any case, Lean is a proof formalization and verification language doubling as a general purpose programming language still in its research phase. If you are interested in how this sounds, you can check it out. If not, there is no need.
I just did a recursive scrape of the tutorial site, converted the html to text, then did a word count using wc and simply divided it by the average number of words per page. Word in this case includes things like '(' and syntax characters.
Regardless it was a rough metric meant to be demonstrative of the level of effort to go through the tutorial.
The point is as an answer to the basic question "what is this and why should I care?" Responding with something over 10 pages is likely unadvisable, yet alone over 100. "Over 100" here is effectively equivalent to "over 5,000". The target should be like 0.25-5, and closer to the 0.25.
Elevator pitch it.
1. For (target customers)
2. Who are dissatisfied with (the current market alternative)
3. Lean is a (new product category)
4. That provides (key problem-solving capability).
5. Unlike (the product alternative),
6. Lean (describe the key product features).
https://www.elevatorpitchessentials.com/essays/CrossingTheCh...
Lean is an interactive theorem prover. It can verify proofs written in Lean by humans. Mathlib is a monolithic library of classical mathematics written in Lean. Mathematicians contributing to Mathlib love it because it has all the interconnected subdisciplines they need in one place, and most of them aren't huge fans of constructive mathematics or univalent mathematics.
Lean is also a strict pure functional programming language with dependent types. You can write correct and maintainable programs in Lean. You can also write proofs showing that a program terminates or it computes the desired answer, etc. Some computer scientists and programmers praise Lean's extensible syntax and editor support.
See also: https://leanprover.zulipchat.com/#narrow/stream/113488-gener...
Awesome!
If you have to listen to such an elevator pitch, you're not the target audience. This is bleeding-edge math/CS research. Talking about a "product" just shows that you have a fundamental misconception regarding what this is all about.
It's a way to describe things. You can describe, for example, the James Webb space telescope or the Large Hadron Collider in that way.
You can also describe say, the Frankfurt school of critical theory or every other programming language.
A product is an act of production here, as in some kind of process. Even things like classes of clouds and rocks can be described in that framework
I don't expect Lean to be an exception
Also to respond to the idea that I'm fundamentally unworthy of an explanation: I'm also not the target audience for the LHC or James Webb but effort has been made to describe it. They don't demand advanced physics degrees to unveil its purpose like they're some kind of secret society.
Don't be coy. Your use of words like "market", "features" or "customers" made it pretty clear what you meant by "product".
> I'm also not the target audience for the LHC or James Webb but effort has been made to describe it.
And there is an effort to describe Lean on their webpage. But I would be curious to know if you would be able to recall the "elevator pitch" you heard for the LHC that doesn't grossly gloss over any kind of relevant actual information. "Customers were dissatisfied because previous colliders were too small, so we made a bigger one. This allows us to hurl particles very fast at each other." Huzzah, you've just been elevator pitched. Do you actually know anything significant about the LHC after that pitch? I sincerely doubt it.
You're also glossing over the fact that the LHC was started in 1998. The James Webb telescope has been in the works since the 90's. Meanwhile, Lean started as a research project in 2013, and Lean 4 is only 1.5 years old. Being angry that scientists have been developing the fundamentals before engaging in outreach is misguided at best.
It's a quote from a famous book, crossing the chasm and it's a trivial exercise that you're refusing to engage with and mocking me in bad faith, violating HN rules.
The LHC example is so simple ChatGPT did it in a single go. Again, this is generative AI
"For particle physics researchers seeking to unravel the cosmos, the Large Hadron Collider (LHC) offers an unparalleled solution. Unlike conventional particle accelerators, the LHC achieves extraordinary collision energies, enabling experiments that mirror the early universe's conditions. This distinctive feature has led to groundbreaking discoveries, notably the Higgs boson. In contrast to other accelerators, the LHC's unmatched power and global scientific network establish it as the premier choice for unlocking the universe's deepest secrets, setting it apart in its capacity to explore uncharted frontiers in particle physics."
In fact, I asked it to do it for Lean and it could do it just fine.
In contrast, the main lean website starts like this:
The Lean (jargon) is a (jargon) developed principally by Leonardo de Moura.
There's this bizarre fetishism for making things inaccessible and then personally belittling and insulting people when they state the obvious.
The other inexplicable behavior is the tendency to give "answers" by pointing to giant manuals that don't answer the question.
This is endemic to ML. Someone asks what say "Vit-L" versus "Vit-H" means and the answer is usually a link to some ~40 page peer reviewed LaTeX that mentions the acronyms but doesn't define it either.
The strategy is to do anything but be transparent and direct.
> "For particle physics researchers seeking to unravel the cosmos, the Large Hadron Collider (LHC) offers an unparalleled solution. Unlike conventional particle accelerators, the LHC achieves extraordinary collision energies, enabling experiments that mirror the early universe's conditions. This distinctive feature has led to groundbreaking discoveries, notably the Higgs boson. In contrast to other accelerators, the LHC's unmatched power and global scientific network establish it as the premier choice for unlocking the universe's deepest secrets, setting it apart in its capacity to explore uncharted frontiers in particle physics."
That's a buzzword soup with barely any actual substance. You're illustrating what I meant. It's also full of jargon (particle accelerators, collision energies, Higgs boson...)
> This is endemic to ML.
Lean and ML are completely unrelated topics.
I'm talking about a culture in mathematics that's intentionally allergic as a matter of custom to effective communication to anyone "outside".
This is so bad that different fields within the discipline can't even understand each other and they wear that as a badge of honor as if being opaque, uninformative, and misleading people is a natural law they're obligated to follow.
It's a truly bizarre social game. A cycle of gaslighting and abuse as an institution.
I had a chance to sleep on this and think it over.
I don't know who goes this deep in to these threads so this is mostly for myself.
My primary critique is from a lifelong love of mathematics. I actually hold a few fancy degrees in the subject.
I cannot stand however, power structures for the sake of power structures. The primary reason I left academia and broke away from the field is my, well, disgust really, with how, I believe willfully obtuse things are.
It's not so much how things are stated although there's problems there, it's the relationship dynamics, interactions, and style of expressions.
Before the rise of the term science, math was called a "natural philosophy" and I really have felt that the mathematics community, at least on the west coast, which is what I've experienced, has an accentuated form of the most off-putting characteristics of philosophy including a steadfast refusal and denial to acknowledge it.
I really think it makes what I consider a beautiful field of study to be hostile, insular and needlessly esoteric.
I still care a lot about it and I want it to be healthier and more open.
Yeah, and a very big difference between Lean and projects such as the LHC or the James Web telescope are that the LHS and the James Web are massive taxpayer-funded projects, so there is an expectation that their significance is clearly explained to those taxpayers (and scientists want continued funding, so it pays to be clear).
Lean started as a small research project hidden away within Microsoft Research, and mathematicians learned about it and have built a community by word of mouth. There is no accountability needed at all for the project, and there's no need to advertise it -- that's not to say that there hasn't been any effort put into advertising it to mathematicians. I just advertised the system myself an hour ago during a talk that explained Lean and Mathlib to a group of mathematicians, computer scientists, and linguists.
Neither of these examples answer my question: What's the point? Perhaps FizzBuzz is a terrible example for such a language, but I don't see anything being "proved" here. Can it do something like static asserts on the output, without actually running the program? E.g. can you prove that the outputs will never be anything else than "Fizz", "Buzz" or "FizzBuzz"?
Sure!
def f (n : Nat) : String := String.append (if n % 3 = 0 then "Fizz" else "") (if n % 5 = 0 then "Buzz" else "") #eval List.map f (List.range 100) theorem poop (n : Nat) : f n = "FizzBuzz" ∨ f n = "Fizz" ∨ f n = "Buzz" ∨ f n = "" := by unfold f split <;> split · exact Or.inl rfl · exact Or.inr (Or.inl rfl) · exact Or.inr (Or.inr (Or.inl rfl)) · exact Or.inr (Or.inr (Or.inr rfl))Oops! I checked the spec and it's supposed do something more like this:
def f (n : Nat) : String := Option.getD (Option.merge String.append (if n % 3 = 0 then "Fizz" else none) (if n % 5 = 0 then "Buzz" else none)) (toString n) #eval List.map (fun k => f (k + 1)) (List.range 100) theorem poop (n : Nat) : f n = "FizzBuzz" ∨ f n = "Fizz" ∨ f n = "Buzz" ∨ f n = toString n := by unfold f split <;> split · exact Or.inl rfl · exact Or.inr (Or.inl rfl) · exact Or.inr (Or.inr (Or.inl rfl)) · exact Or.inr (Or.inr (Or.inr rfl))Thank you. I must admit, I have trouble making sense of it.
Just for comparison, in Typescript you can write:
The return type of this function will be inferred as "Fizz"|"Buzz"|"FizzBuzz"|"".function f(n:number){ if (n%3==0 && n%5==0) return "FizzBuzz" if (n%3==0) return "Fizz" if (n%5==0) return "Buzz" return ""; }Then, I can write:
The type of fizzBuzz100 will be inferred as ("Fizz"|"Buzz"|"FizzBuzz")[];function *iFizzBuzz(steps:number){ for (let i=0; i<steps; i++){ const fb = f(i); if (fb) yield fb; } } const fizzBuzz100 = Array.from(iFizzBuzz(100));Lean will not create a custom type to infer for each function; it will either infer an existing type or report failure; it will also not automatically coerce to String. What you see above is a proof in tactic mode of your specification as a theorem. If you want to guarantee the outputs of a function, you need to specify a custom type. For instance:
inductive FizzBuzz where | fizz | buzz | fizzBuzz | none def fizzBuzz (n : Nat) : FizzBuzz := if n % 15 == 0 then .fizzBuzz else if n % 3 == 0 then .fizz else if n % 5 == 0 then .buzz else .none instance : ToString FizzBuzz where toString : FizzBuzz → String | .none => "" | .fizz => "Fizz" | .buzz => "Buzz" | .fizzBuzz => "FizzBuzz" def stringFizz (n : Nat) : String := toString <| fizzBuzz n def printFizz (n : Nat) : IO Unit := do println! s!"{fizzBuzz n}"
Awesome! Where did the "split_ifs" tactic come from though? Mathlib? In your opinion does it make sense to do program verification without using Mathlib, or would you recommend just using it pretty much all the time?
Yes split_ifs is in Mathlib so I have replaced it with split (twice) which is in Core. I believe there is also an intermediate level Std. I'm not sure why you'd want to avoid Mathlib but I daresay it's possible for many types of problem.
The examples were not meant to answer your question, but the question kristopolous set. Ask your question at top level and some of us, perhaps myself, will answer.
The goal of Lean is to be a programming language used to prove math theorems. Looking at a FizzBuzz implementation and balking at the complexity is utterly missing the point.
I’ve been very excited by lean, but every time I try to set things up I get riddled with exceptions, errors, library incompatibilities, lean 3/4 problems. Tuts or documentation that is outdated or just doesn’t work. It has made me wonder, is this just really really alpha software, are they working at a bleeding rate? Idk, but I’ve been enticed multiple times by the promise of lean, maybe I’m just missing some info or should stick it out or just wait until it gets more stable. Anyone have any insight here?
Yes, you should expect some frustration, especially if you want to configure things your way.
The least painful pipeline should be the following (only follow the instructions at the pages I am listing, as otherwise things may get too confusing):
1) Install lean as a VS Code extension lean4 following : https://leanprover.github.io/lean4/doc/quickstart.html
2) Read about using the build system `lake` here : https://leanprover.github.io/lean4/doc/setup.html
3) Note that this does not install mathlib4; leave that for later.
4) Start playing around with basic examples in VS Code by reading the beginning sections of https://leanprover.github.io/functional_programming_in_lean/...
5) If something does not work on break, ask in the Zulip chat; the devs are gathering pain points to improve tooling every day.
If this seems too painful, indeed you may want to wait a bit for the tooling to improve.
Re Lean 3/4 problems: the port of mathlib from Lean 3 to Lean 4 just finished this summer, and unfortunately there's still going to be some confusion between the two for a little while! The mathlib community has been working on getting the documentation to all refer to Lean 4 -- if you find anything old please point it out on the Zulip. There's usually someone around who can fix it relatively quickly.
I think it's better to think of it as bleeding-edge research software rather than alpha software. There might be a little bit of culture shock if you're used to industry-oriented software, but part of this stable version announcement is that there's a new Lean organization that now has resources to improve the experience.
Does Lean have something similar to Haskell's List comprehension [1] or some kind of set builder notation for functional programming purposes?
[1]: Example: `[x*2 | x <- [1..10]]`
It has the following which means the same as what you wrote:
The syntax is flexible enough that you could build your own:do let x ← List.range' 1 10; return x^2macro "[" r:term "|" preamble:doElem "]" : term => `(do $preamble; return $r) #eval [x^2 | let x ← List.range' 1 10]Here's an extensible one I wrote a while back for just List, but I haven't tested it in a while:
(Your doElem idea is a good one though)declare_syntax_cat compClause syntax "for " term " in " term : compClause syntax "if " term : compClause syntax "[" term " | " compClause,* "]" : term macro_rules | `([$t:term |]) => `([$t]) | `([$t:term | for $x in $xs]) => `(List.map (λ $x => $t) $xs) | `([$t:term | if $x]) => `(if $x then [$t] else []) | `([$t:term | $c, $cs,*]) => `(List.join [[$t | $cs,*] | $c]) #eval [x+1| for x in [1,2,3]] -- [2, 3, 4] #eval [4 | if 1 < 0] -- [] #eval [4 | if 1 < 3] -- [4] #eval [(x, y) | for x in List.range 5, for y in List.range 5, if x + y <= 3] -- [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (3, 0)]Huh that is really cool! Thanks for the example!
Surely you can define such notation, but why? The following is just as clear and concise, and does not rely on any extensions:
For example:(. * 2) <$> [1,2,3]def byTwo (inputList : List Nat) := (. * 2) <$> inputList #eval byTwo [1, 2, 3] -- [2, 4, 6]> but why?
Why not? I was curious, Haskell is the functional language I know. Lean is the language I do not know.
Since Lean leans even heavier towards mathematics, set builder style notation seems like a natural fit. Now whether or not such notation is actually needed or worth it, that is a whole different question.
That's not exactly clear to mathematicians, who tend to complain about the "ascii art operators".
I think you'll usually see
rather than using `<$>`. There's also `inputList |>.map (. * 2)`, but I haven't seen it in any mathlib theory code yet, just Lean core or in metaprogramming.def byTwo (inputList : List.Nat) := inputList.map (. \* 2)
never understood the appeal of this syntax over standard do notation or just fmap.
List comprehensions read like math which we know from school. Do notation reads like Haskell which is fine but less accessible to non-Haskellers. Fmap is somewhat less convenient for slightly more complex examples such as
[x*y | x <- [1..10], y <- [2,3,5]]For that you'd use Applicative
Admittedly also not accessible to non-haskellers. But on the other hand, if you're going to learn a language, you ought to learn its idioms at some point.(*) <$> [1..10] <*> [2,3,5] -- or liftA2 (*) [1..10] [2,3,5]That being said, nequo's request is not unreasonable; given Lean's advanced metaprogramming facilities, their request should be easy to implement.
The nice thing nequo's example illustrates is rank polymorphism: list comprehensions work with lists, products of two, three, four,... lists with the same easy notation : `[n-ary function | x_1 <- List_1, ..., x_n <- List_n]`. It is quite nice to have this, especially for complex numerical operations.
Note also that unlike Lean 3, in Lean 4 `List` does not inherently implement `Applicative` or `Monad`, so your code cannot work as is.
Mathlib4 provides a `Monad List` instance, which you can see at https://leanprover-community.github.io/mathlib4_docs/Mathlib...
Haskell has always been a language where there are many ways to skin any particular cat, for reasons from ergonomics to expressiveness to theoretical niceness or practicality. "Learn the idioms" has nothing to do with it. Why didn't you just use do-notation instead, for example, than write some applicative mess where it isn't needed?
It's not rocket science why someone would ask this. I don't always use list comprehensions. But sometimes I do. They have open arity and the syntax doesn't as often require things like parenthesis to handle fixity conflicts between other (non-applicative) operators. They are asking about list comprehensions, just because they think it's nice. It is a very simple question and talking about applicative is irrelevant.
That's perfectly fine Haskell, but I wouldn't say that using Applicative is much of a Lean idiom. Especially in the mathlib, people prefer using custom notation that looks like math notation or using the underlying functions directly rather than by using generic point-free notations. For example, you'll see `⨆ i, s i` for a supremum across the values of `s`, vs a point-free version.
Is Lean a Category?
(like much debated: is Hask(ell) a Category)
"In this section we set up the theory so that Lean's types and functions between them can be viewed as a `LargeCategory` in our framework."
So it seems to be proven that there is a Category Lean!
https://github.com/leanprover-community/mathlib4/blob/master...
Yes for the fragment of total and noncomputable functions which mathematicians use. For partial functions (which Lean also supports) I think the same arguments hold as for the "Haskell Category".
It took me about a minute and more than one click to reach a page which told me what lean IS. Hint: In the Readme, it's the Home Page link, then About.
Came here to comment the same. The entire GH project seems to assume the visitor knows what Lean is.
Does anyone know if Lean 4 has encoded much category theory?
Everything I can think of and more of what I'll ever need:
https://github.com/leanprover-community/mathlib4/tree/master...
Though I did not find Topos Theory.
There are definitions for sheaves, Grothendieck topologies and sites[1] which were extensively used in the Liquid Tensor Experiment[2]
[1] https://github.com/leanprover-community/mathlib4/tree/master...
[2] https://leanprover-community.github.io/blog/posts/lte-final/
Thanks,
and there is Subobject, which looks like the subobject classifier.
https://github.com/leanprover-community/mathlib4/blob/master...
To clarify, this is not really related to subobject classifiers. This defines subobjects of `X` as equivalence classes of monomorphisms with target `X`.
We don't have any topos theory, that's right. But all the prerequisites are there. If you're interested in working on it I strongly suggest to ask on Zulip.
Here's a Lean 3 development of a bunch of topos theory https://github.com/b-mehta/topos/tree/master/src , but it's not in the maths library (and now needs to be updated to Lean 4, although the community have had great success with that kind of project; one million lines of mathlib was translated from Lean 3 to Lean 4 using a combination of automation and human work)
As others said above, `mathlib4` has quite a lot of Sheaf theory, and in particular the category of sheaves of Sets (i.e. Types) over an arbitrary site. In this sense, it is possible to talk about Grothendieck toposes. We don't have the characterization in terms of Giraud's axioms, though.