textmetrics
Compare text, build edit scripts, and estimate English readability.
String comparisons normalize to NFC using the target runtime and compare grapheme clusters. Generic list operations compare elements directly. Word and character classification uses Unicode 15.1 data; runtime normalization and grapheme segmentation may use another Unicode version.
Readability functions return raw formula values and use an English syllable heuristic. Use myers or patience to build an edit script, then to_unified to render individual lines.
Types
Represent one element of an edit script.
Equal retains an element present in both inputs, Delete removes an old element, and Insert adds a new element. A script is a List(Edit(a)).
pub type Edit(a) {
Equal(item: a)
Insert(item: a)
Delete(item: a)
}
Constructors
-
Equal(item: a) -
Insert(item: a) -
Delete(item: a)
Report unequal grapheme counts after NFC normalization.
pub type HammingError {
LengthMismatch(left: Int, right: Int)
}
Constructors
-
LengthMismatch(left: Int, right: Int)
Report a non-finite prefix scale, a scale outside 0.0..0.25, or a negative prefix cap.
pub type JaroWinklerError {
PrefixScaleOutOfRange(got: Float)
PrefixMaxNegative(got: Int)
}
Constructors
-
PrefixScaleOutOfRange(got: Float) -
PrefixMaxNegative(got: Int)
Identify the old or new filename rejected by unified diff validation.
pub type NameField {
OldName
NewName
}
Constructors
-
OldName -
NewName
Pair an original candidate string with its similarity score.
pub type Ranked {
Ranked(label: String, score: Float)
}
Constructors
-
Ranked(label: String, score: Float)
Report input that has too few words or sentences for a formula.
at_least is the required count and got is the observed count.
pub type ReadabilityError {
TooFewWords(at_least: Int, got: Int)
TooFewSentences(at_least: Int, got: Int)
}
Constructors
-
TooFewWords(at_least: Int, got: Int)The input had fewer than
at_leastwords.gotis the actual count. -
TooFewSentences(at_least: Int, got: Int)The input had fewer than
at_leastsentences.gotis the actual count.
Group consecutive edit steps of the same kind.
Each variant holds its elements in their original order. edit_runs produces nonempty runs.
pub type Run(a) {
EqualRun(items: List(a))
InsertRun(items: List(a))
DeleteRun(items: List(a))
}
Constructors
-
EqualRun(items: List(a)) -
InsertRun(items: List(a)) -
DeleteRun(items: List(a))
Values
pub fn automated_readability_index(
text: String,
) -> Result(Float, ReadabilityError)
Calculate the raw Automated Readability Index for English text.
Use 4.71 * characters / words + 0.5 * words / sentences - 21.43. Characters follow count_characters’s letter-like grapheme definition. Return the formula value without clamping. Input without words returns TooFewWords.
pub fn coleman_liau_index(
text: String,
) -> Result(Float, ReadabilityError)
Calculate the raw Coleman-Liau index for English text.
Use 0.0588 * L - 0.296 * S - 15.8, where L and S are letter-like graphemes and sentences per 100 words. Return the formula value without clamping. Input without words returns TooFewWords.
pub fn count_characters(text: String) -> Int
Count letter-like graphemes used by the readability formulas.
Use the same Unicode categories and exclusions as count_words, counting individual graphemes rather than runs. Letters and decimal digits from different scripts count. Empty input returns zero.
pub fn count_paragraphs(text: String) -> Int
Count runs of nonblank lines separated by blank lines.
Ignore leading and trailing blank lines. Empty input returns zero.
pub fn count_polysyllables(text: String) -> Int
Count words whose estimated syllable count is at least three.
Use the same word boundaries and syllable heuristic as count_syllables. Do not exclude proper nouns or inflected words.
pub fn count_sentences(text: String) -> Int
Count sentence boundaries and an unfinished final sentence.
Recognize ., !, ?, …, 。, ., !, ?, ।, and ॥. Consecutive terminators count as one boundary. A trailing nonempty fragment counts as a sentence. Empty input returns zero.
A period followed directly by a letter or digit does not end a sentence, as in 3.50 or example.com. Common English abbreviations such as Dr., Mrs., and weekday or month abbreviations also keep their period. For multi-period abbreviations such as e.g., p.m., and U.S.A., a following capitalized word starts a new sentence; a lowercase word continues the current one.
pub fn count_syllables(text: String) -> Int
Sum syllable estimates over the words in a text.
Use count_words’s boundaries and count_syllables_in_word’s heuristic. Input without words returns zero.
pub fn count_syllables_in_word(word: String) -> Int
Estimate a word’s syllable count with an English heuristic.
Normalize to NFC and lowercase, keep ASCII letters and the supported accented Latin vowels, then count vowel groups. A noninitial y counts as a vowel. Subtract a trailing silent e except after consonant-plus-l, as in table. Return at least one for every nonempty input, including input with no retained letters. Empty input returns zero.
This function does not detect language. Applying the heuristic to a non-English word can return more than one syllable.
pub fn count_words(text: String) -> Int
Count maximal runs of letter-like graphemes.
After NFC normalization, accept a grapheme when its first code point has Unicode 15.1 category Letter, Mark, Decimal_Number, or Letter_Number. Whitespace, punctuation, symbols, unassigned code points, and other numbers such as ① separate words. An ASCII digit followed within its grapheme by a keycap mark (U+20E3) or emoji presentation selector (U+FE0F) also separates words. Empty input returns zero.
Examples
count_words("hello, world!")
// 2
count_words("")
// 0
pub fn damerau_levenshtein(left: String, right: String) -> Int
Count edits including adjacent transpositions between NFC-normalized strings.
Insertion, deletion, substitution, and transposition each cost one. A substring may participate in more than one edit. For example, "CA" to "ABC" has distance two; optimal_string_alignment gives three.
pub fn did_you_mean(
query: String,
candidates: List(String),
max_distance: Int,
) -> List(String)
Select candidates within a whole-string Levenshtein distance and sort them by distance.
Compare NFC-normalized graphemes, returning the original candidate strings. Keep input order for equal distances and retain duplicate candidates. Empty candidates or a negative distance limit return an empty list. Use list.first on the result when only one suggestion is needed.
pub fn edit_cost(script: List(Edit(a))) -> Int
Count insertion and deletion steps in an edit script.
Equal steps contribute zero. For a script from myers, this is the minimum insertion-and-deletion distance.
pub fn edit_runs(script: List(Edit(a))) -> List(Run(a))
Group consecutive edits of the same kind, preserving their element order.
Empty input returns an empty list.
pub fn flesch_kincaid_grade(
text: String,
) -> Result(Float, ReadabilityError)
Calculate the raw Flesch-Kincaid grade estimate for English text.
Use 0.39 * words / sentences + 11.8 * syllables / words - 15.59. Return the formula value without clamping. Input without words returns TooFewWords.
pub fn flesch_reading_ease(
text: String,
) -> Result(Float, ReadabilityError)
Calculate the raw Flesch Reading Ease score.
Use 206.835 - 1.015 * words / sentences - 84.6 * syllables / words. Higher values indicate easier English text. The result can be below zero or above 100; no clamping is applied. Input without words returns TooFewWords.
pub fn gunning_fog(
text: String,
) -> Result(Float, ReadabilityError)
Calculate the raw Gunning Fog index for English text.
Use 0.4 * (words / sentences + 100 * polysyllables / words). A polysyllable has at least three estimated syllables. Do not apply the original formula’s exclusions for proper nouns, compounds, or inflected words. Return the formula value without clamping. Input without words returns TooFewWords.
pub fn hamming(
left: String,
right: String,
) -> Result(Int, HammingError)
Count differing positions in two strings with equal grapheme counts.
Normalize both inputs to NFC first. Return Error(LengthMismatch(left, right)) when their normalized grapheme counts differ. Two empty inputs return Ok(0).
Examples
hamming("karolin", "kathrin")
// Ok(3)
hamming("ab", "abc")
// Error(LengthMismatch(2, 3))
pub fn jaro(left: String, right: String) -> Float
Calculate Jaro similarity over NFC-normalized graphemes.
Return a score from zero to one based on matching graphemes and half the mismatches in their matched sequences. Two empty inputs return 1.0; exactly one empty input returns 0.0.
pub fn jaro_winkler(
left: String,
right: String,
prefix_scale scale: Float,
prefix_max maximum: Int,
) -> Result(Float, JaroWinklerError)
Calculate Jaro similarity with a boost for a shared prefix.
Require a finite prefix_scale in 0.0..0.25 and prefix_max >= 0. Validate the scale, then the cap, before checking the input strings. Apply the boost only when the Jaro score is greater than 0.7. Cap the prefix contribution so that scale times prefix length does not exceed one. Conventional parameters are 0.1 and 4.
Normalize inputs to NFC. Two empty inputs return Ok(1.0); exactly one empty input returns Ok(0.0). A zero scale or zero prefix cap gives the Jaro score. Different strings can score 1.0 when the prefix boost saturates.
pub fn levenshtein(left: String, right: String) -> Int
Count the minimum single-grapheme insertions, deletions, and substitutions between two strings.
Normalize both strings to NFC before comparing graphemes. Two empty strings have distance zero; the distance from an empty string is the other’s grapheme count.
Examples
levenshtein("kitten", "sitting")
// 3
levenshtein("Á", "A\u{0301}")
// 0
pub fn levenshtein_list(left: List(t), right: List(t)) -> Int
Count the minimum insertions, deletions, and substitutions between two lists.
Compare elements with equality. Do not normalize strings stored inside the lists. Empty lists follow the same rules as levenshtein.
pub fn levenshtein_similarity(
left: String,
right: String,
) -> Float
Convert Levenshtein distance to a similarity score from zero to one.
Return 1 - distance / max_length, using NFC-normalized grapheme counts. Two empty strings return 1.0; exactly one empty string returns 0.0. A score of 1.0 means the normalized strings are equal.
pub fn longest_common_subsequence(
left: List(t),
right: List(t),
) -> List(t)
Return one longest subsequence shared by two lists.
Preserve element order and compare elements directly. If several longest subsequences exist, do not rely on which is chosen. Empty input on either side returns an empty list.
pub fn longest_common_subsequence_length(
left: List(t),
right: List(t),
) -> Int
Return the length of a longest subsequence shared by two lists.
Compare elements directly without string normalization. Return zero when either list is empty.
pub fn myers(old: List(a), new: List(a)) -> List(Edit(a))
Build a shortest insertion-and-deletion edit script between two lists.
Use Myers’ algorithm and compare elements directly. Applying recover_old and recover_new to the script reconstructs the inputs. Substitution is represented by a deletion and an insertion.
pub fn optimal_string_alignment(
left: String,
right: String,
) -> Int
Count insertions, deletions, substitutions, and adjacent transpositions with each substring edited at most once.
Normalize strings to NFC and compare graphemes. This restricted distance can exceed damerau_levenshtein and does not satisfy the triangle inequality.
pub fn patience(
old: List(String),
new: List(String),
) -> List(Edit(String))
Build an edit script using unique common lines as anchors.
Use patience diff for List(String) and Myers diff between anchors. Compare strings directly without NFC normalization. The script reconstructs both inputs, but need not minimize the edit count.
pub fn rank_jaro_winkler(
query: String,
candidates: List(String),
top_n: Int,
) -> List(Ranked)
Return up to the requested number of candidates in descending Jaro-Winkler score order.
Use prefix scale 0.1 and cap 4. Compare NFC-normalized graphemes, retain original candidate strings, and preserve input order on ties. Empty candidates or a nonpositive result limit return an empty list.
pub fn recover_new(script: List(Edit(a))) -> List(a)
Recover the new list from an edit script’s Equal and Insert steps.
pub fn recover_old(script: List(Edit(a))) -> List(a)
Recover the original list from an edit script’s Equal and Delete steps.
pub fn smog(text: String) -> Result(Float, ReadabilityError)
Calculate the SMOG grade estimate for English text with at least 30 sentences.
Use 1.043 * sqrt(30 * polysyllables / sentences) + 3.1291. First reject input without words with TooFewWords, then reject fewer than 30 sentences with TooFewSentences.
pub fn smog_extrapolated(
text: String,
) -> Result(Float, ReadabilityError)
Apply the SMOG formula to an English sample without the 30-sentence minimum.
Require at least one word and one sentence, returning TooFewWords or TooFewSentences when the corresponding requirement fails. Short samples extrapolate the formula beyond the sample size required by smog.
pub fn sorensen_dice(
left: String,
right: String,
ngram_size size: Int,
) -> Result(Float, Nil)
Compare multisets of NFC-normalized grapheme n-grams with the Sørensen-Dice coefficient.
Require ngram_size >= 1; otherwise return Error(Nil). Count repeated n-grams with their multiplicity. If both inputs are shorter than the n-gram size, return Ok(1.0) for equal normalized strings and Ok(0.0) otherwise. If only one lacks n-grams, return Ok(0.0).
Different strings can have the same n-gram multiset and score 1.0.
Examples
sorensen_dice("night", "nacht", ngram_size: 2)
// Ok(0.25)
sorensen_dice("a", "b", ngram_size: 0)
// Error(Nil)
pub fn to_unified(
script: List(Edit(String)),
old_name old_name: String,
new_name new_name: String,
context_lines context: Int,
) -> Result(String, UnifiedError)
Render an edit script of individual lines as a unified diff.
Each element must be one line without a line terminator. Output uses LF-terminated lines and does not retain whether an input file lacked its final newline.
Reject filenames containing LF, CR, NUL, or tab, and reject a negative context count. Validate the old name, new name, then context count, even for an unchanged script. Zero context is valid. An unchanged script returns Ok("").