# How do you calculate first and follow sets?

Table of Contents

## How do you calculate first and follow sets?

For any production rule A → αBβ,

- If ∈ ∉ First(β), then Follow(B) = First(β)
- If ∈ ∈ First(β), then Follow(B) = { First(β) – ∈ } ∪ Follow(A)

## What is first () and follow () functions?

FIRST and FOLLOW help us to pick a rule when we have a choice between two or more r.h.s. by predicting the first symbol that each r.h.s. can derive.

## Why do we calculate first and follow?

So FOLLOW can make a Non-terminal to vanish out if needed to generate the string from the parse tree. The conclusions is, we need to find FIRST and FOLLOW sets for a given grammar, so that the parser can properly apply the needed rule at the correct position.

## What are the rules to calculate first information?

Rules to compute FIRST set:

- FIRST(X) = FIRST(Y1)
- If FIRST(Y1) contains Є then FIRST(X) = { FIRST(Y1) – Є } U { FIRST(Y2) }
- If FIRST (Yi) contains Є for all i = 1 to n, then add Є to FIRST(X).

## Is there a standard algorithm for computing first and FOLLOW sets?

The standard algorithm for computing FIRST and FOLLOW sets is discussed in most compiler textbooks and books on parsing algorithms. I would be surprised if you were taking a course where this was covered and had no assigned reading or materials provided on this topic.

## How to calculate first and FOLLOW sets in grammar?

A graphical method has been given to calculate the First and Follow sets of a grammar which is easier to apply for a learner or a student… This graphical method is applied to the Expression Grammar to find the First and Follow sets and we also check its correctness with the help of derivations.

## How to calculate the first and follow function?

Before calculating the first and follow functions, eliminate Left Recursion from the grammar, if present. We calculate the follow function of a non-terminal by looking where it is present on the RHS of a production rule. The given grammar is left recursive. So, we first remove left recursion from the given grammar.

## How to compute follow ( a ) for all nonterminals?

To compute FOLLOW(A) for all nonterminals A, apply the following rules until nothing can be added to any FOLLOW set: 1. Place $ in FOLLOW(S), where S is the start symbol and $ is the input right endmarker. 2. If there is a production A ⇒ αΒβ , then everything in FIRST(β ), except for ε, is placed in FOLLOW(B).