SLR(1)文法分析器构造中ComputeFirst()和ComputeFollow()函数错误参数修复
SLR(1)文法分析器构造中ComputeFirst()和ComputeFollow()函数错误参数修复
在使用C#构造SLR(1)文法分析器时,ComputeFirst()和ComputeFollow()函数中可能会遇到'无法从“string”转换为“char”'的错误参数问题。该问题通常是由于在使用HashSet
**问题代码:**C#// ... 其他代码 ...
if (!temp.SetEquals(first[node.Left])){ first[node.Left].UnionWith(temp); flag = true;}
// ... 其他代码 ...
解决方案:
将HashSet
**修改后的代码:**C#// SLRNode 类public class SLRNode{ public string Left; public string Right; public HashSet
public SLRNode(string Left, string Right) { this.Left = Left; this.Right = Right; First = new HashSet<string>(); Follow = new HashSet<string>(); }}
// ... 其他代码 ...
// ComputeFollow() 函数public void ComputeFollow(){ // 初始化 Follow 集 foreach (char c in Nchar) { follow.Add(c.ToString(), new HashSet
// 计算 Follow 集 bool flag = true; while (flag) { flag = false; foreach (SLRNode node in SLRproNum) { for (int i = 0; i < node.Right.Length; i++) { if (Nchar.Contains(node.Right[i])) { HashSet<string> temp = new HashSet<string>(); bool canEpsilon = true; for (int j = i + 1; j < node.Right.Length; j++) { if (Echar.Contains(node.Right[j])) { temp.UnionWith(first[node.Right[j].ToString()]); // 使用字符串作为键 if (!first[node.Right[j].ToString()].Contains('ε')) { canEpsilon = false; break; } } else { canEpsilon = false; temp.UnionWith(first[node.Right[j].ToString()]); // 使用字符串作为键 break; } } if (canEpsilon) { temp.UnionWith(follow[node.Left]); } if (!temp.SetEquals(follow[node.Right[i].ToString()])) // 使用字符串作为键 { follow[node.Right[i].ToString()].UnionWith(temp); flag = true; } } } if (node.Right.EndsWith(Nchar.ToString())) { if (!follow[node.Left].SetEquals(follow[node.Right[node.Right.Length - 1].ToString()])) // 使用字符串作为键 { follow[node.Right[node.Right.Length - 1].ToString()].UnionWith(follow[node.Left]); flag = true; } } } }}
总结:
通过将HashSet
原文地址: https://www.cveoy.top/t/topic/f0Oo 著作权归作者所有。请勿转载和采集!