Table of Contents

Lab

Lab-01 - Expresii regulate

Key insights:

Objectives:

Resources (tentative):

Exercises

I. What is the regular expression for the following languages:

Solution: $ E=011$
Obs: By definition the correct expression is $ E=((01)1)$ , but we won't write them when not needed and we use a precedence rule to reduce the number of parantheses in regular expressions as much as possible (Kleene Star > Concatenation > Union).

Solution: $ E=a \cup b$
Obs: By definition the correct expression is $ E=(a \cup b)$ , but we can remove parentheses for the same reason as above.

Solution: $ E=(0 \cup 1)^{*}$

Solution: $ E=01001010100001(0 \cup 1)$

Solution: $ E=(0 \cup 1)^{*}0$

Solution: $ E=(0 \cup 1)^{*}01 \cup 1(0 \cup 1)$

Solution: $ E=y^{*}xy^{*}xy^{*}$
Obs: $ \#_x(w)$ denotes number of $ x$ in $ w$ .

Solution: $ E=(b^{*}ab^{*}ab^{*})^{*}$

Solution: $ E=(x \cup y)^{*}x(x \cup y)^{*}$

Solution: $ E=((a \cup b \cup c)^{*}a(a \cup b \cup c)^{*}b(a \cup b \cup c)^{*}) \cup ((a \cup b \cup c)^{*}b(a \cup b \cup c)^{*}a(a \cup b \cup c)^{*})$

Solution: $ E=a^{*}b^{*}$

Solution: $ E=\epsilon$

Solution: $ E=\emptyset$

Lab x - JFlex

Installing JFlex

A complete, platform-dependent set of installation instructions can be found here. In a nutshell, JFlex comes as a binary app jflex.

The structure of a flex file

Consider the following simple JFlex file:

import java.util.*;
 
%%
 
%class HelloLexer
%standalone
 
%{
  public Integer words = 0;
%}
 
LineTerminator = \r|\n|\r\n
 
%%   
 
[a-zA-Z]+ { words+=1; }
{LineTerminator} { /* do nothing*/ }

Suppose the above file is called Hello.flex. Running the command jflex Hello.flex will generate a Java class which implements a lexer.

Each JFlex file (such as the above), contains 5 sections:

Compiling a Hello World project

After performing:

jflex Hello.flex

we obtain HelloLexer.java which contains the HelloLexer public class implementing our lexer. We can easily include this class in our project, e.g.:

import java.io.*;
import java.util.*;
 
public class Hello {
  public static void main (String[] args) throws IOException {
    HelloLexer l = new HelloLexer(new FileReader(args[0]));
 
    l.yylex();
 
    System.out.println(l.words);
 
 
  }
}

After compiling:

javac HelloLexer.java Hello.java

and running:

java Hello

we obtain:

 
 

 6

at standard output.

Recall that the option standalone tells the lexer to print unmatched words. In our example, those unmatched words are whitespaces.

Application - parsing lists

Consider the following BNF grammar which describes lists:

<integer> ::= [0-9]+
<op> ::= "++" | ":"
<element> ::= <integer> | <op> | <list>
<sequence> ::= <element> | <element> " " <sequence> 
<list> ::= | "()" | "(" <sequence> ")"

The following are examples of lists:

(1 2 3)
(1 (2 3) 4 ())
(1 (++ (: 2 (3)) (4 5)) 6)

Your task is to: