Community draft, October 2026.
This guide describes how to write programs, libraries and tools in Lean 4, focusing on general-purpose software, not math.
It's a community project, not an official document of the Lean FRO or of Mathlib.
Main resources used here are Lean's own style guide and naming conventions for the standard library. Some rules were borrowed from other language ecosystems where they make sense for Lean, e.g Haskell, OCaml
- Names should be guessable (Lean naming conventions).
- Give each claim the strongest guarantee it admits: a type, then a theorem, then a property test, then an example (Paul Butcher, issue #1).
"Use", "Write" and "Don't" mean always, "Prefer" and "Avoid" mean usually, and "Consider" means it's often worth it. Once Lean's official formatter is released (FRO roadmap), its output takes precedence over the layout rules.
- Use a
structurefor a value with several parts and aninductivefor alternatives (data-structure-inductive). - Define structures with named fields instead of passing tuples around (
data-own-types). - Wrap a primitive in a single-field structure when its values must not be mixed with others, such as IDs (
data-wrappers). - Check a value once where it enters the program, and pass a type that carries the check (
data-boundary). - Use
abbrevfor exact synonyms,structurefor new domain types, and neverdeffor type synonyms (data-abbrev). - Use
extendsonly when one structure clearly "is a" kind of another (data-extends). - Avoid indexed families in APIs, except in code that resembles a typed language (
data-indexed-families). - Derive instances instead of writing them, and derive
Reprfor every data type (data-deriving). - Build structures with named fields unless the order of the fields is obvious (
data-constructors). - Update a structure with
{ s with field := value }instead of copying fields by hand (data-update).
- Keep program logic in pure functions and
IOin a thin outer layer (effects-pure-core). - Pass shared configuration through
ReaderT, and define the application's monad withabbrev(effects-config). - Put acquire and release in a
with…helper built withtry … finally(effects-resources). - Use
IOfor sequential code,Taskfor parallel computation andAsyncfor programs that mostly wait on I/O (effects-concurrency). - Don't
#evalactions with side effects in library files (effects-eval). - Handle special cases first and return early, so the main path isn't nested (
do-early-return). - Unwrap an
Optionwithlet some x := e | fallbackwhen the failure case is short (do-let-else). - Use
let mutandforwhen they're clearer than a fold or a state monad (do-mutation). - Use
modifyto update state, instead ofgetfollowed byset(effects-modify). - Use
(← action)inline for a result you use once, andlet x ← actionotherwise (do-nested-actions). - End
doblocks withreturn x, and usepure xoutside them (do-return).
- Return
Optionfor one obvious failure andExceptwhen the caller needs to know which failure happened (errors-option-except). - Give a library an inductive error type with a
ToStringinstance (errors-types). - In
IOcode, throw errors instead of returning default values (errors-io). - Add context to an error at the level that knows it, such as the file being read (
errors-context). - Don't replace a missing value with a default when its absence can mean that the program is misconfigured (
errors-defaults). - Use
panic!and!functions only when essential: for bugs, where you can't pass a proof instead, and never to reject bad input (errors-panics). - Say in the docstring how a function fails when its type doesn't already say so (
errors-document).
- Log where the code makes a decision that its result can't express (
logging-decisions). - Record the value that decided the branch, not just the outcome (
logging-values). - Log what was asked for, since a span records only the route (
logging-requests). - Don't log ordinary success when a span already records the request (
logging-success).
- Make public only what callers need (
api-surface). - Use the module system in libraries, with a plain
public sectionin program files (api-modules). - Mark helpers
private, or put them in anInternalnamespace (api-private). - Mark a declaration
protectedif its short name would clash afteropen(api-protected). - Deprecate a public declaration before you rename, remove or change it, and note every such change in the changelog (
api-deprecation). - Avoid
variablein program code (api-variable).
- Use
UpperCamelCasefor types and namespaces,lowerCamelCasefor functions, values and fields, andsnake_casefor theorems (naming-case). - Put the functions about a type in the namespace named after the type (
naming-namespaces). - Name
Boolfunctions as questions, as inisEmpty, andProppredicates withIs, as inIsSorted(naming-predicates). - Mark failure in the name with
?for anOption,!for a panic andDfor a default (naming-failure). - Name conversions
toXandofX, neverfromX(naming-conversions). - Add
Mto the name of a variant that runs in a monad, as inmapMandforM(naming-monadic). - Don't name a variant of a public function by adding
'(naming-primes). - Write acronyms of four or more letters as words, as in
Json, and shorter ones in one case, as inIO(naming-acronyms). - Use short local names only by convention, such as
xsfor arrays,accfor accumulators andifor indices (naming-locals). - Leave instances anonymous (
naming-instances). - Name packages in lowercase and modules in
UpperCamelCase, with file paths that match (naming-files).
- Give every top-level definition explicit argument types and an explicit result type (
functions-signatures). - Make an argument implicit, with braces, when later arguments determine it (
functions-implicit). - Turn off
autoImplicit, so a misspelled type name is an error (functions-auto-implicit). - Put single-use helpers in a
whereclause, and name a recursive helpergo(functions-helpers). - Give optional parameters default values, and put options that several functions share in a structure (
functions-options). - Pass
Boolarguments by name, as in(quiet := true)(functions-bool-args). - Use
|>,|>.and<|to avoid nested parentheses, and don't use$(functions-pipelines). - Write lambdas as
fun x => e, never withλor↦(functions-lambdas).
- Define a type class only when several types will have instances and code is generic over them (
classes-when). - Ask for the weakest class a function needs, so it works for more types (
classes-weakest). - Make
BEqagree withHashable, andOrdwithLTandLE(classes-consistent). - Add a coercion only when every source value has an obvious counterpart in the target type (
classes-coercions). - For a recursive type, write the recursive function in the type's namespace and have the instance call it (
classes-recursive). - Write instances with
where, one method per line (classes-where).
- Use
Arrayfor sequences you build, index or update, andListfor small ones you take apart from the front (collections-array). - Keep a single reference to an array you're updating, so Lean can update it in place (
collections-sharing). - Loop over elements rather than indices, and prefer
xs[i]?or a proof toxs[i]!(collections-iterate). - Use
Std.HashMapfor lookups andStd.TreeMapwhen key order matters (collections-maps).
- Prefer structural recursion, and give a measure with
termination_bywhen the recursion isn't structural (recursion-structural). - Mark a function
partialonly when it might not terminate, or nobody knows whether it does (recursion-partial). - Use
for,whileandrepeatinstead of recursive helpers that only loop (recursion-loops). - Use loops or accumulators for recursion over large inputs (
recursion-deep).
- Prove claims as theorems by default, and fall back to property tests and examples only when a proof doesn't work out (
proofs-first). - Keep the simple version of an optimized function as its specification, and prove that the two agree (
proofs-spec). - Time-box a proof, and if it fails, write a property test with a comment that records the obstacle (
proofs-timebox). - When a module with property tests changes, check whether each property can now be proved (
proofs-recheck). - Keep short lemmas next to their definitions, and move longer proofs to their own module (
proofs-location). - Prefer
grind,omegaandsimpto long manual proofs, and squeezesimpcalls that aren't the last step (proofs-automation). - Name a theorem after what it states, in
snake_case, starting from the conclusion (proofs-names). - Don't commit
sorry(proofs-sorry).
- Test what types and proofs don't cover (
tests-coverage). - Don't write tests that only restate literals from the source (
tests-literals). - Put tests in a
<Pkg>Testlibrary run bylake test, or in atest/subproject when a library's tests need extra dependencies (tests-library). - Check results with
#guard_msgsand#guard(tests-guard-msgs). - Compare whole outputs with saved copies only where their exact form is the contract, and review every regenerated copy (
tests-golden). - Use an executable test driver for tests that run
IO(tests-runtime). - Test properties of your own code that aren't proved yet on random inputs, with
Plausible.Testable.checkrather than theplausibletactic (tests-property). - In test files that are modules, import the code under test with
meta import(tests-meta-import).
- Write a docstring when the name and type leave something unsaid, and not one that restates them (
docs-when). - Begin a file with a module docstring, with a
#title, when the file needs more explanation than its code gives (docs-module). - Start a function's docstring with a verb such as "Returns", and a type's with a noun phrase (
docs-summary). - Show short examples in docstrings, and check them with tests (
docs-examples). - Put a short docstring on one line, and the delimiters of a longer one on lines of their own (
docs-layout).
- Explain why in comments, and don't restate what the code does (
comments-why). - Write down every invariant that your types don't enforce (
comments-invariants). - Leave history and dead code to version control, and unfinished work to the issue tracker (
comments-history).
- Get standard notation by implementing classes such as
AddandGetElem(macros-classes). - Use macros for syntax sugar, and elaborators when the translation needs types or decisions (
macros-macro-or-elab). - Make notation
scopedunless every user of your library needs it (macros-scoped). - Don't add
macro_rulesthat cover only some uses of existing syntax (macros-overlap). - Make your notation appear in Lean's output the way users write it (
macros-output).
- Don't add
@[inline]or@[specialize]without a measurement that shows they help (perf-measure). - Prefer
@[csimp]with a proof to@[implemented_by], which Lean doesn't check (perf-implemented-by). - Keep
unsafecode in small functions with a safe interface, and say in a comment why it's needed (perf-unsafe). - Keep
@[extern]declarations in one small module behind a safe Lean API (perf-ffi).
- Start from the layout
lake newcreates, with a smallMain.lean(project-layout). - Commit
lean-toolchainandlake-manifest.json, and require dependencies at release tags (project-dependencies). - Declare files that you embed with
include_stras Lake inputs in the library'sneeds, or editing them rebuilds nothing (project-embedded-files). - Set
autoImplicit = falsein the Lake configuration (project-options). - Check for warnings in CI with
lake build --wfail, and don't setwarningAsErrorin a library (project-warnings). - Keep Lean's built-in linters on (
project-linters). - Don't mix reformatting with other changes (
project-formatting).
- Order each file as licence comment,
module, imports, module docstring, then code (layout-file). - Indent with two spaces, never with tabs (
layout-indentation). - Keep lines under 100 characters (
layout-line-length). - Put single spaces around
:,:=,|,::,=>,←and infix operators (layout-spaces). - Start top-level commands at column 0, and don't indent inside
namespaceorsection(layout-top-level). - Indent the continuation lines of a long declaration header by four spaces, and never start a line with the colon (
layout-headers). - Split long expressions at argument boundaries, with infix operators at the end of the line (
layout-splitting). - Put
matcharms at the column of thematch, without padding to align the arrows (layout-match). - Start
where,deriving,termination_byanddecreasing_byat the column of the declaration they belong to (layout-where). - In a multi-line structure instance, put
{at the end of the line before it and}on its own line (layout-structure-instances). - Put
doon the same line as the:=,=>or←before it (layout-do).
Open an issue or a pull request. Every Lean example has to compile:
python3 tools/check_examples.pyThe text of this guide is licensed under CC BY 4.0. The code examples, tools/ and research/scripts/ are licensed under Apache-2.0. Material quoted in research/ stays under its original licence, listed for each source in research/index.md.