Zuletzt aktiv 2 weeks ago

anduin's Avatar anduin hat die Gist bearbeitet 2 weeks ago. Zu Änderung gehen

1 file changed, 1 insertion

combinator.cs

@@ -23,6 +23,7 @@ public class Program
23 23 };
24 24
25 25 Console.WriteLine("--- 构造解析器 ---");
26 + Func<string, string> parser = Combinator.Fix(grammarFactory);
26 27 string testInput = "AAAB";
27 28 Console.WriteLine($"\n--- 开始解析输入: \"{testInput}\" ---");
28 29

anduin's Avatar anduin hat die Gist bearbeitet 2 weeks ago. Zu Änderung gehen

1 file changed, 49 insertions

combinator.cs(Datei erstellt)

@@ -0,0 +1,49 @@
1 + using System;
2 +
3 + public 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 +
38 + public 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 + }
Neuer Älter