Ostatnio aktywny 2 weeks ago

Rewizja 68794fa3acaf97e721ebe61eea074891abfc3394

combinator.cs Surowy
1using System;
2
3public class Program
4{
5 public static void Main()
6 {
7 Func<Func<string, string>, Func<string, string>> grammarFactory = (self) =>
8 {
9 return (input) =>
10 {
11 if (string.IsNullOrEmpty(input))
12 return "";
13
14 if (input.StartsWith("A"))
15 {
16 Console.WriteLine($"[逻辑层] 发现字符 'A',吃掉它。剩余字符串: \"{input.Substring(1)}\" -> 呼叫 self 递归");
17 return self(input.Substring(1));
18 }
19
20 Console.WriteLine($"[逻辑层] 遇到非 'A' 字符 ('{input[0]}'),递归停止。");
21 return input;
22 };
23 };
24
25 Console.WriteLine("--- 构造解析器 ---");
26 string testInput = "AAAB";
27 Console.WriteLine($"\n--- 开始解析输入: \"{testInput}\" ---");
28
29 string remaining = parser(testInput);
30
31 Console.WriteLine($"\n--- 解析完成 ---");
32 Console.WriteLine($"原始输入: {testInput}");
33 Console.WriteLine($"剩余部分: {remaining}");
34 }
35}
36
37
38public static class Combinator
39{
40 public static Func<T, R> Fix<T, R>(Func<Func<T, R>, Func<T, R>> f)
41 {
42 return input =>
43 {
44 Func<T, R> self = Fix(f);
45 Func<T, R> actualLogic = f(self);
46 return actualLogic(input);
47 };
48 }
49}