algorithm - 从语法生成第一个集合

标签 algorithm ll

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/

相关文章:

c - 计算网格上连接组的相邻空点的有效方法

algorithm - 范围之间的 GCD

c++ - 如何将非常大的十进制数转换为阶乘数系统?

parsing - 用于上下文无关文法的FIRST和FOLLOW集的计算算法

grammar - 为什么LL语法不能是左递归的?

algorithm - 如何在 Haskell 中编写 N 元树遍历函数

algorithm - 国际象棋:Alpha-Beta 中的错误

linux ll 输出解释

shell - shell 运算符的优先级