Extractive Summarization
File: Summarizer.lean
An extractive summarizer picks the most useful sentences from a text and returns them unchanged. This one counts how often each word appears in the whole text, ignores common words, and scores each sentence by the mean count of its words.
The Code
1 -- lean --run Summarizer.lean (extractive text summarization)
2 import Std.Data.HashMap
3
4 def stopWords : List String :=
5 ["the", "a", "an", "in", "on", "at", "to", "for", "of", "and", "or",
6 "is", "are", "was", "were", "it", "that", "this", "with", "as", "by",
7 "from", "be", "has", "have", "its"]
8
9 -- Lowercased runs of letters and digits
10 def words (text : String) : List String :=
11 let init : List String × List Char := ([], [])
12 let (res, acc) := text.toList.foldl (init := init)
13 fun (res, acc) ch =>
14 if ch.isAlphanum then (res, ch.toLower :: acc)
15 else if acc.isEmpty then (res, acc)
16 else (String.ofList acc.reverse :: res, [])
17 let res :=
18 if acc.isEmpty then res else String.ofList acc.reverse :: res
19 res.reverse
20
21 -- Split after each '.', '!' or '?'
22 def splitSentences (text : String) : List String :=
23 let init : List String × List Char := ([], [])
24 let (res, acc) := text.toList.foldl (init := init)
25 fun (res, acc) ch =>
26 if ch == '.' || ch == '!' || ch == '?' then
27 (String.ofList (ch :: acc).reverse :: res, [])
28 else (res, ch :: acc)
29 let all := (String.ofList acc.reverse :: res).reverse
30 (all.map (·.trimAscii.toString)).filter (· ≠ "")
31
32 -- The n best sentences in their original order. A sentence scores the
33 -- mean document frequency of its words; stop words count as zero.
34 def summarize (text : String) (n : Nat := 2) : List String :=
35 let sentences := splitSentences text
36 let freqs : Std.HashMap String Nat :=
37 sentences.foldl (init := ∅) fun freqs s =>
38 (words s).foldl (init := freqs) fun freqs w =>
39 if stopWords.contains w then freqs
40 else freqs.insert w (freqs.getD w 0 + 1)
41 let scored := sentences.zipIdx.map fun (s, idx) =>
42 let ws := words s
43 let score :=
44 if ws.isEmpty then 0.0
45 else (ws.foldl (· + freqs.getD · 0) 0).toFloat / ws.length.toFloat
46 (score, idx, s)
47 let top := (scored.mergeSort (fun a b => a.1 ≥ b.1)).take n
48 (top.mergeSort (fun a b => a.2.1 ≤ b.2.1)).map (·.2.2)
49
50 def text : String :=
51 "Lean 4 is a functional programming language and an interactive " ++
52 "theorem prover with a rich dependent type system. " ++
53 "It features type classes, hygienic macros, and a metaprogramming " ++
54 "framework that allows programmers to create domain-specific " ++
55 "languages. " ++
56 "Extractive summarization algorithms score sentences based " ++
57 "on significant word frequencies across a document. " ++
58 "In this example, we calculate term frequencies and rank " ++
59 "sentences to produce a concise summary. " ++
60 "Lean 4 continues to empower developers to build " ++
61 "verified programming and mathematical systems with high " ++
62 "productivity."
63
64 def main : IO Unit := do
65 let count := (splitSentences text).length
66 IO.println s!"Original text: {count} sentences.\n"
67 IO.println "Extractive 2-Sentence Summary:"
68 for s in summarize text 2 do
69 IO.println s!" • {s}"
How It Works
import Std.Data.HashMaploads the hash map from the standard library. Animportmust come before any other code in the file.wordsis the same function astokenizein the BM25 chapter.splitSentencesfolds over the characters and closes a sentence at each.,!, or?.trimAsciiremoves spaces from both ends and returns a slice of the string.toStringcopies the slice to a new string.freqsis aStd.HashMap String Nat. The code builds it with two nested folds.∅is the empty map.freqs.getD w 0reads the count forwand returns 0 if the word is absent.insertreturns a new map. Lean updates the map in place when no other code holds a reference to it.zipIdxpairs each sentence with its position.- The last two lines sort twice. The first sort orders by score and keeps the top
n. The second sort puts those sentences back in their order in the text.
summarize scores with document frequency, not tf-idf, and divides by the count of every word including stop words. A long sentence with common content words can win. The two sorts are stable, so equal scores keep the earlier sentence in the final order. The bullet in the output is a plain Unicode character.
splitSentences closes a sentence at every period, so abbreviations such as Dr. and decimals split, and it keeps the punctuation in the sentence. It also returns a final piece with no end mark; the empty-string filter removes it when the text ends with a period.
Checking a Score
The first selected sentence has 13 words. Two of them, sentences and frequencies, appear twice in the document. Nine content words appear once, and on and a are stop words, so they count zero. The sum is 13 and the mean is 13/13 = 1.0. The second selected sentence scores 0.938, so it ranks second.
TextRank builds a graph of sentence similarities, and LSA uses a term-document matrix; both handle repetition and sentence similarity better than a mean frequency. For a short demo, this method is easier to check by hand.
Try this: add a length penalty (divide by the square root of the word count) or a lead bias (add a small bonus for early sentences), then compare the summary with the current output.
Lean 4 Notes
Imports and namespaces. Lean loads a small core library into every file. Other parts of the standard library need an import line. Names have a namespace prefix: the hash map type is Std.HashMap. You can write the full name, as this file does, or write open Std once and then use HashMap.
Immutable collections. Every Lean value is immutable. freqs.insert w n does not change freqs. It returns a map that has the new entry. That sounds slow, but Lean counts the references to each value. When insert runs and no other reference to the map exists, Lean reuses the memory and changes it in place. The fold in summarize passes the map from step to step and never keeps an old copy, so each insert is an in-place update.
Two dots. (· + freqs.getD · 0) has two dots, so it is a function of two arguments: fun acc w => acc + freqs.getD w 0. The first dot is the first argument.
The empty map. ∅ is the empty value for any collection type. Lean picks the type from the context. Here the let line says freqs is a Std.HashMap String Nat.
Nested tuples. (score, idx, s) is a pair of score and the pair (idx, s). So a.1 is the score, a.2.1 is the index, and a.2.2 is the sentence. The last line of summarize uses all three.
Statements where a Bool is expected. filter takes a function that returns a Bool. (· ≠ "") is a statement about strings. Lean can decide it by computing, so it converts the statement to a Bool for you.
Long string literals. text joins twelve short strings with ++, which keeps each source line short.
Running It
1 $ lean --run Summarizer.lean
2 Original text: 5 sentences.
3
4 Extractive 2-Sentence Summary:
5 • Extractive summarization algorithms score sentences based on significant word frequencies across a document.
6 • Lean 4 continues to empower developers to build verified programming and mathematical systems with high productivity.
Using It
Change the 2 in main to get a longer summary. Add words to stopWords for your subject area. To summarize a file, read it with IO.FS.readFile and pass the text to summarize.