Algorithm寻找第一组:
Given a grammar with the rules A1 → w1, ..., An → wn, we can compute the Fi(wi) and Fi(Ai) for every rule as follows:
initialize every Fi(Ai) with the empty set
set Fi(wi) to Fi(wi) for every rule Ai → wi, where Fi is defined as follows:
Fi(a w' ) = { a } for every terminal a
Fi(A w' ) = Fi(A) for every nonterminal A with ε not in Fi(A)
Fi(A w' ) = Fi(A) \ { ε } ∪ Fi(w' ) for every nonterminal A with ε in Fi(A)
Fi(ε) = { ε }
add Fi(wi) to Fi(Ai) for every rule Ai → wi
do steps 2 and 3 until all Fi sets stay the same.
语法:
A -> B C c
A -> g D B
B -> EPSILON | b C D E
C -> D a B | c a
D -> EPSILON | d D
E -> g A f | c
这website生成第一个集合如下:
Non-Terminal Symbol First Set
A g, ε, b, a, c, d
B ε, b
C a, c, ε, d
D ε, d
E g, c
但算法说 Fi(A w' ) = Fi(A) 对于每个 ε 不在 Fi(A) 中的非终结符 A
所以根据这个算法的 First(A) 不应该包含ε
。 First(A) = {g, b, a, c, d}
。
问:上述语法的 First(A) = First(B) - ε U First(C) U {g}
?
这video同样遵循上述算法,不选择ε。
最佳答案
First(B) = {ε, b}
First(D) = {ε, d}
First(E) = {g, c}
First(C) = {c, d, a}
First(A) = {b, g, c, d, a}
例子:
X -> Y a | b
Y -> c | ε
First(X) = {c, a, b}
First(Y) = {c, ε}
First(X) 没有 ε,因为如果用 ε 替换 Y,则 First(Y a) 等于 First(ε a) = {a}
首先在我的github上设置实现。
编辑:更新链接
https://github.com/amirbawab/EasyCC-CPP/blob/master/src/syntax/grammar/Grammar.cpp#L229
计算第一个和后续集都可以在上面的新链接上找到。
关于algorithm - 从语法生成第一个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37886271/