# CS 315-02 Quizzes

1. Date: Sept. 25, 2017
Question: Give the rightmost derivation of the string "a = b + const" in the following grammar.
<program> → <stmts>
<stmts> → <stmt> | <stmt> ; <stmts>
<stmt> → <var> = <expr>
<var>  → a | b | c | d
<expr> → <term> + <term> | <term> - <term>
<term> → <var> | const

<program> ⇒ <stmts>
⇒ <stmt>
⇒ <var> = <expr>
⇒ <var> = <term> + <term>
⇒ <var> = <term> + const
⇒ <var> = <var> + const
⇒ <var> = b + const
⇒ a = b + const

2. Date: Oct. 9, 2017
Question: Write a lex specification that will filter out only the integers in the input file.
Sample execution:
\$scanner
ABc57xy-34ab
57-34

%option main
%%
[+-]?[0-9]+ printf("%s", yytext);
. ;

3. Date: Oct. 26, 2017
Question: What is the output of the following python program?
x=0
def outer():
x=1
def inner():
nonlocal x
x=2
print("inner:", x)
inner()
print("outer:", x)

outer()
print("global:", x)

inner: 2
outer: 2
global: 0

4. Date: Oct. 30, 2017
Question: What are the referencing environments for each of the points in the following perl program?
sub A {
my \$x=2;     # \$x uses static scoping
local \$y=3;  # \$y uses dynamic soping
# point1
B();
}

sub B {
# point2
C();
}

sub C {
# point3
}

\$x = 1;
A();
# point4

Point1: \$x in sub A, \$y in sub A
Point2: \$x in global, \$y in sub A
Point3: \$x in global, \$y in sub A
Point4: \$x in global

5. Date: Nov. 23, 2017
Question: Implement the factorial function using counter-controlled loop in Python. Assume that the parameter is a natural number.

def factorial(n):
result = 1
for x in range(1,n+1):
result = result * x
return result

6. Date: Dec. 18, 2017
Question: What does each of the following Scheme expressions yield?
(let ((x 2)) (+ x 3))
(let ((f +) (x 2)) (f x 3))
(let ((f +) (x 2) (y 3))(f x y))
(let ((+ *))(+ 2 3))
(let ((double-cons (lambda (x) (cons x x)))) (double-cons 'a))
(map cons '(a b c) '((a) (b c) (d)))