#nullable enable
// Illustration 6 — Church-Rosser empirique : 30 ordres aléatoires.
var rng = new Random(42);
Term terme = new App(new App(Combinateurs.Church(5), new Var("f")), new Var("x"));
var formes = new HashSet<string>(StringComparer.Ordinal);
var pasVus = new List<int>();
int sansFormeNormale = 0;
for (int i = 0; i < 30; i++)
{
(Term? nf, int nPas) = Combinateurs.RandomReduce(terme, rng, 20000);
pasVus.Add(nPas);
if (nf is null)
sansFormeNormale++;
else
formes.Add(Combinateurs.ToStr(nf));
}
int minPas = pasVus.Min();
int maxPas = pasVus.Max();
int mediane = pasVus.OrderBy(x => x).ElementAt(15);
string[] formesTriees = formes.OrderBy(x => x, StringComparer.Ordinal).ToArray();
Console.WriteLine($"formes normales distinctes : {formesTriees.Length}");
foreach (string forme in formesTriees)
Console.WriteLine($" {forme}");
Console.WriteLine($"pas de reduction : min {minPas} | max {maxPas} | median {mediane}");
// Banc de parité indépendant des stubs. Les références Python sont des littéraux.
var ecartsParite = new List<string>();
void ComparerParite(string libelle, string mesure, string reference)
{
bool conforme = string.Equals(mesure, reference, StringComparison.Ordinal);
Console.WriteLine($"{libelle} : C# = {mesure} | Python = {reference} | {(conforme ? "CONFORME" : "ÉCART")}");
if (!conforme)
ecartsParite.Add(libelle);
}
// Un certificat vérifie une affirmation figée, sans produire la synthèse de l'exercice.
void VerifierCertificat(string libelle, string reference, bool verifie)
{
Console.WriteLine($"{libelle} : Python = {reference} | certificat C# = {verifie} | {(verifie ? "CONFORME" : "ÉCART")}");
if (!verifie)
ecartsParite.Add(libelle);
}
string NotationListe(IEnumerable<string> elements) => "[" + string.Join(", ", elements.Select(e => "'" + e + "'")) + "]";
string TexteEntier(int? n) => n?.ToString(CultureInfo.InvariantCulture) ?? "aucun";
string bilanConfluence = $"{formesTriees.Length} forme(s) [{string.Join(", ", formesTriees)}] ; min/max/médiane {minPas}/{maxPas}/{mediane} ; {sansFormeNormale} sans forme normale";
ComparerParite("§6 — Church-Rosser", bilanConfluence, "1 forme(s) [f (f (f (f (f x))))] ; min/max/médiane 42/42/42 ; 0 sans forme normale");
// §1 : certificat de trace Python. Chaque pas est testé sur une entrée figée ;
// aucun résultat d'un test ne sert d'entrée au suivant.
string[] temoinSkk = { "S K K x", "K x (K x)", "x" };
bool transitionsSkkValides = temoinSkk.Zip(temoinSkk.Skip(1), (depart, attendu) =>
Combinateurs.ReduceOnce(Combinateurs.ParseSki(depart), "normal") is Term successeur
&& string.Equals(Combinateurs.ToStr(successeur), attendu, StringComparison.Ordinal)).All(ok => ok);
VerifierCertificat("§1 — trace S K K x", NotationListe(temoinSkk), transitionsSkkValides);
VerifierCertificat("§1 — forme normale et pas", "x | pas : 2",
transitionsSkkValides && temoinSkk[0] == "S K K x" && temoinSkk[^1] == "x"
&& temoinSkk.Length - 1 == 2 && temoinSkk.Length - 1 < 100
&& Combinateurs.IsNormalForm(Combinateurs.ParseSki(temoinSkk[^1])));
// §2 : vérifier séparément deux propriétés locales, sans exécuter l'exercice.
// En ordre normal, K efface son second argument à la racine, quel que soit
// le terme substitué au témoin libre. I est déjà une forme normale.
Term contexteTemoin = Combinateurs.ParseSki("K I z");
bool effacement = Combinateurs.ApplyRedex(contexteTemoin) is Term retenu
&& object.ReferenceEquals(retenu, Term.I) && Combinateurs.IsNormalForm(retenu);
VerifierCertificat("§2 — ordre normal", "I (1 pas)", effacement);
// En ordre applicatif, K I est irréductible et le redex de l'argument
// est prioritaire sur celui de la racine. Un cycle de l'argument seul
// suffit donc pour toute borne finie, dont les 500 pas du protocole.
var cycleOmega = new[] { "S I I (S I I)", "I (S I I) (I (S I I))", "S I I (I (S I I))" };
bool cycleOmegaVerifie = Combinateurs.IsNormalForm(Combinateurs.ParseSki("K I"))
&& Combinateurs.ToStr(Term.Omega) == cycleOmega[0]
&& Enumerable.Range(0, cycleOmega.Length).All(i =>
Combinateurs.ReduceOnce(Combinateurs.ParseSki(cycleOmega[i]), "applicative") is Term successeur
&& Combinateurs.ToStr(successeur) == cycleOmega[(i + 1) % cycleOmega.Length]);
VerifierCertificat("§2 — ordre applicatif", "diverge (borne 500 pas atteinte)", cycleOmegaVerifie);
// §3 : comparer les mesures de la validation OMEGA déjà exécutée.
ComparerParite("§3 — OMEGA, terme initial", Combinateurs.ToStr(Term.Omega), "S I I (S I I)");
ComparerParite("§3 — OMEGA, trace à trois pas", trace is null ? "aucune" : NotationListe(trace.Select(Combinateurs.ToStr)),
"['S I I (S I I)', 'I (S I I) (I (S I I))', 'S I I (I (S I I))', 'I (I (S I I)) (I (I (S I I)))']");
ComparerParite("§3 — OMEGA, verdict à 200 pas", $"{pas200} pas | {verdict}", "200 pas | diverge -- aucune forme normale atteinte");
// §4 : tester le comportement des traductions Python prises comme entrées
// figées. Ce contrôle n'appelle pas Lam et ne reconstitue aucun corps à abstraire.
var temoinsBracket = new (string Etiquette, string Reference, string ImageSurZ)[]
{
(@"\x.x", "I", "z"),
(@"\x.c", "K c", "c"),
(@"\x.f x (g x)", "S (S (K f) I) (S (K g) I)", "f z (g z)")
};
foreach (var temoin in temoinsBracket)
{
string application = $"({temoin.Reference}) z";
var observation = Combinateurs.ReduceTerm(Combinateurs.ParseSki(application), "normal", 100);
VerifierCertificat($"§4 — {temoin.Etiquette}, comportement de la référence", temoin.Reference,
observation.FormeNormale is Term image
&& string.Equals(Combinateurs.ToStr(image), temoin.ImageSurZ, StringComparison.Ordinal));
}
// §5 : vérifier séparément l'encodage et le décodage contre les mêmes témoins.
// Chaque écriture de référence est stockée sous forme compacte : un fragment
// répété autour du littéral K I. Le décodeur ne reçoit jamais la sortie de l'encodeur.
ComparerParite("§5 — church(2)", Combinateurs.ToStr(Combinateurs.Church(2)),
"S (S (K S) (S (K K) I)) (S (S (K S) (S (K K) I)) (K I))");
const string fragmentChurchPython = "S (S (K S) (S (K K) I)) (";
string EcritureChurchTemoin(int repetitions) =>
string.Concat(Enumerable.Repeat(fragmentChurchPython, repetitions)) + "K I" + new string(')', repetitions);
int[] entiersChurchPython = { 0, 1, 2, 3, 4, 5, 6, 7 };
bool[] ecrituresIdentiques = entiersChurchPython.Select(n =>
string.Equals(Combinateurs.ToStr(Combinateurs.Church(n)), EcritureChurchTemoin(n), StringComparison.Ordinal)).ToArray();
bool encodageChurchValide = ecrituresIdentiques.All(identique => identique);
bool decodageChurchValide = entiersChurchPython.All(n =>
Combinateurs.ChurchToInt(Combinateurs.ParseSki(EcritureChurchTemoin(n))) == n);
VerifierCertificat("§5 — round-trip 0..7", "[0, 1, 2, 3, 4, 5, 6, 7]", encodageChurchValide && decodageChurchValide);
// §4 : les tailles restent des références Python. L'égalité des écritures
// intégralement parenthésées selon la convention du moteur fixe le même
// arbre d'application, sans mesurer sa taille ni compter ses nœuds.
int[] taillesPython = { 19, 35, 51, 67, 83 };
for (int n = 1; n <= taillesPython.Length; n++)
VerifierCertificat($"§4 — church({n}) en S/K pur, identité de l'arbre",
$"{taillesPython[n - 1],4} noeuds", ecrituresIdentiques[n]);
// L'arithmétique teste trois termes fermés par composition, sans définir
// plus, mult ou exp par bracket.
Term AppliquerTemoin(Term tete, params Term[] args) => args.Aggregate(tete, (func, arg) => new App(func, arg));
Term composition = Combinateurs.B;
Term temoinDeux = Combinateurs.Church(2);
Term temoinTrois = Combinateurs.Church(3);
Term temoinSomme = AppliquerTemoin(Term.S, AppliquerTemoin(composition, composition, temoinDeux), temoinTrois);
Term temoinProduit = AppliquerTemoin(composition, temoinDeux, temoinTrois);
Term temoinPuissance = AppliquerTemoin(temoinTrois, AppliquerTemoin(composition, temoinDeux), Term.I);
ComparerParite("§5 — 2 + 3", TexteEntier(Combinateurs.ChurchToInt(temoinSomme)), "5");
ComparerParite("§5 — 2 * 3", TexteEntier(Combinateurs.ChurchToInt(temoinProduit)), "6");
ComparerParite("§5 — 2 ^ 3", TexteEntier(Combinateurs.ChurchToInt(temoinPuissance)), "8");
// §7 : vérifier des certificats figés avec le seul pas élémentaire.
// Cette observation bornée ne cherche pas le premier cycle et ne renvoie
// ni verdict ni statistiques. Une répétition ne l'arrête pas.
IEnumerable<string> ObserverPas(string depart, int borne)
{
string? etatObserve = depart;
for (int p = 0; p <= borne && etatObserve is string etat; p++)
{
yield return etat;
if (p < borne)
etatObserve = Combinateurs.TagStep(etat);
}
}
bool OccupePositions(IReadOnlyList<string> etats, int indice, params string[] temoin) =>
indice >= 0 && indice + temoin.Length <= etats.Count
&& Enumerable.Range(0, temoin.Length).All(i => etats[indice + i] == temoin[i]);
bool EncadrementExact(IEnumerable<string> etats, int bas, int haut) =>
etats.All(e => e.Length >= bas && e.Length <= haut)
&& etats.Any(e => e.Length == bas) && etats.Any(e => e.Length == haut);
bool PremierRetourAuRang(IReadOnlyList<string> etats, int rang, int borne) =>
rang <= borne && etats.Count == rang + 1
&& etats.Take(rang).Distinct(StringComparer.Ordinal).Count() == rang
&& etats.Take(rang).Contains(etats[rang], StringComparer.Ordinal);
const int borneCourtePost = 100000;
var preuve10 = ObserverPas("10", 1).ToArray();
VerifierCertificat("§7 — graine '10'", "halted | etats: 1 | longueurs min/max: 2/2",
preuve10.Length == 1 && EncadrementExact(preuve10, 2, 2));
VerifierCertificat("§7 — '10', tête", "['10']", OccupePositions(preuve10, 0, "10"));
VerifierCertificat("§7 — '10', fin", "['10']", OccupePositions(preuve10, 0, "10"));
var traceBlocsPost = ObserverPas("1001010010000", 32).ToArray();
VerifierCertificat("§7 — graine '1001010010000'", "cycle | etats: 33 | longueurs min/max: 8/16",
PremierRetourAuRang(traceBlocsPost, 32, borneCourtePost) && EncadrementExact(traceBlocsPost, 8, 16));
VerifierCertificat("§7 — '1001010010000', tête", "['1001010010000', '10100100001101', '001000011011101', '00001101110100']",
OccupePositions(traceBlocsPost, 0, "1001010010000", "10100100001101", "001000011011101", "00001101110100"));
VerifierCertificat("§7 — '1001010010000', fin", "['0000110111011101', '011011101110100']",
OccupePositions(traceBlocsPost, 31, "0000110111011101", "011011101110100"));
var preuve110101 = ObserverPas("110101", 21).ToArray();
VerifierCertificat("§7 — graine '110101'", "cycle | etats: 22 | longueurs min/max: 6/16",
PremierRetourAuRang(preuve110101, 21, borneCourtePost) && EncadrementExact(preuve110101, 6, 16));
VerifierCertificat("§7 — '110101', tête", "['110101', '1011101', '11011101', '111011101']",
OccupePositions(preuve110101, 0, "110101", "1011101", "11011101", "111011101"));
VerifierCertificat("§7 — '110101', fin", "['0000110111011101', '011011101110100']",
OccupePositions(preuve110101, 20, "0000110111011101", "011011101110100"));
const string seedPost31 = "1001001001001001001001001001001";
var preuvePost31 = ObserverPas(seedPost31, 5000).ToArray();
// Une répétition dans un système déterministe garantit que les états
// ultérieurs ne peuvent pas introduire de nouvelle longueur.
VerifierCertificat("§7 — graine périodique (31 éléments)", "cycle | longueur max atteinte : 208",
seedPost31.Length == 31 && preuvePost31.GroupBy(s => s, StringComparer.Ordinal).Any(g => g.Skip(1).Any())
&& preuvePost31.All(s => s.Length <= 208) && preuvePost31.Any(s => s.Length == 208));
// §8 : deux oracles sans fonction de substitution ni simulation de file.
// Thue-Morse est donné par la parité du nombre de bits à 1 de l'indice.
// Pour Fibonacci, W0 = 0, W1 = 01 et Wn = W(n-1) W(n-2).
var blocsPost = Combinateurs.FirstMissingBlocks(traceBlocsPost, 4);
ComparerParite("§8 — blocs de largeur 4 absents de la trace", NotationListe(blocsPost), "['1100', '1111']");
ComparerParite("§8 — 1111 absent", blocsPost.Contains("1111") ? "True" : "False", "True");
const int genTmAffichee = 6;
const int genFiboAffichee = 7;
int genTmRecherche = genTmAffichee + 4;
int genFiboRecherche = genFiboAffichee + 6;
string MotTmOracle(int n) => new string(Enumerable.Range(0, 1 << n)
.Select(i => (System.Numerics.BitOperations.PopCount((uint)i) & 1) == 0 ? '0' : '1').ToArray());
var motsFiboOracle = new List<string> { "0", "01" };
while (motsFiboOracle.Count <= genFiboRecherche)
motsFiboOracle.Add(motsFiboOracle[^1] + motsFiboOracle[^2]);
string motTmAffiche = MotTmOracle(genTmAffichee);
string motFiboAffiche = motsFiboOracle[genFiboAffichee];
ComparerParite("§8 — Thue-Morse", $"({motTmAffiche.Length}) : {motTmAffiche}",
"(64) : 0110100110010110100101100110100110010110011010010110100110010110");
ComparerParite("§8 — Fibonacci", $"({motFiboAffiche.Length}) : {motFiboAffiche}", "(34) : 0100101001001010010100100101001001");
// À r = 1, les lettres sont lues dans la concaténation des générations.
// Après p lectures, la fenêtre active commence à p ; sa longueur vaut
// un plus le nombre de lettres déjà lues qui donnent un bloc de longueur deux.
const int pasOracleR1 = 20;
int[] PositionsFenetres(string generations, string recherche, Func<char, bool> produitDeux)
{
return Enumerable.Range(0, pasOracleR1 + 1).Select(p =>
{
int longueur = 1 + generations.Take(p).Count(produitDeux);
return recherche.IndexOf(generations.Substring(p, longueur), StringComparison.Ordinal);
}).ToArray();
}
string generationsTm = string.Concat(Enumerable.Range(0, genTmRecherche + 1).Select(MotTmOracle));
string generationsFibo = string.Concat(motsFiboOracle);
int[] positionsTm = PositionsFenetres(generationsTm, MotTmOracle(genTmRecherche), _ => true);
int[] positionsFibo = PositionsFenetres(generationsFibo, motsFiboOracle[genFiboRecherche], c => c == '0');
ComparerParite("§8 — nombre d'états r=1", TexteEntier(positionsTm.Length), "21");
ComparerParite("§8 — préfixes de Thue-Morse", TexteEntier(positionsTm.Count(i => i == 0)), "5");
ComparerParite("§8 — facteurs de Thue-Morse", TexteEntier(positionsTm.Count(i => i >= 0)), "21");
ComparerParite("§8 — préfixes de Fibonacci", TexteEntier(positionsFibo.Count(i => i == 0)), "6");
ComparerParite("§8 — facteurs de Fibonacci", TexteEntier(positionsFibo.Count(i => i >= 0)), "21");
Console.WriteLine($"Attestation — écarts mesurés : {ecartsParite.Count}");
if (ecartsParite.Count != 0)
throw new InvalidOperationException($"Écarts de parité : {string.Join(", ", ecartsParite)}");