Skip to content

Instantly share code, notes, and snippets.

@m-dekorte
Last active June 11, 2025 10:01
Show Gist options
  • Select an option

  • Save m-dekorte/875d26262c54a262b20d980d83796bdb to your computer and use it in GitHub Desktop.

Select an option

Save m-dekorte/875d26262c54a262b20d980d83796bdb to your computer and use it in GitHub Desktop.
getAllSubstrings M function | Generate all possible contiguous substring combinations from a string.
let
/* This was an exercise just for fun. Who knows, it might have a real-world application... */
/* Generate every possible substring combination from a string */
getAllSubstrings = (s as text, optional makeDistinct as logical, optional ignoreCase as logical) as list =>
let
c = if ignoreCase ?? false then Comparer.OrdinalIgnoreCase else Comparer.Ordinal,
n = Text.Length(s),
sub = List.TransformMany(
{0..n-1},
each {_+1..n},
(x, y) => Text.Range(s, x, y-x)
),
ans = if makeDistinct ?? false then List.Distinct(sub, c) else sub
in
ans,
/* AllSubstrings */
EXAMPLE_1 = getAllSubstrings("ABBA"),
/* Distinct Substrings */
EXAMPLE_2 = getAllSubstrings("ABBa", true),
/* Distinct Substrings, ignoring case */
EXAMPLE_3 = getAllSubstrings("ABBa", true, true)
in
EXAMPLE_3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment