combinator.cs
· 1.4 KiB · C#
Raw
using System;
public class Program
{
public static void Main()
{
Func<Func<string, string>, Func<string, string>> grammarFactory = (self) =>
{
return (input) =>
{
if (string.IsNullOrEmpty(input))
return "";
if (input.StartsWith("A"))
{
Console.WriteLine($"[逻辑层] 发现字符 'A',吃掉它。剩余字符串: \"{input.Substring(1)}\" -> 呼叫 self 递归");
return self(input.Substring(1));
}
Console.WriteLine($"[逻辑层] 遇到非 'A' 字符 ('{input[0]}'),递归停止。");
return input;
};
};
Console.WriteLine("--- 构造解析器 ---");
string testInput = "AAAB";
Console.WriteLine($"\n--- 开始解析输入: \"{testInput}\" ---");
string remaining = parser(testInput);
Console.WriteLine($"\n--- 解析完成 ---");
Console.WriteLine($"原始输入: {testInput}");
Console.WriteLine($"剩余部分: {remaining}");
}
}
public static class Combinator
{
public static Func<T, R> Fix<T, R>(Func<Func<T, R>, Func<T, R>> f)
{
return input =>
{
Func<T, R> self = Fix(f);
Func<T, R> actualLogic = f(self);
return actualLogic(input);
};
}
}
| 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 | } |