Practical Session 1

advertisement
Compiler principles, PS1
A compiler is a computer program that transforms source code written in a
programming language into another computer language.
Structure of a compiler:
Scanner
Parser
Semantic analyzer
Code generation




Scanner (lexical analysis) - converts a sequence of characters into a sequence
of tokens.
Parser (syntactic analysis) – checks for correct syntax and builds a hierarchical
structure (parse tree) implicit in the input tokens.
Semantic analyzer (semantic analysis) – compiler adds semantic information to
the parse tree and builds the symbol table. This phase performs semantic checks
such as type checking, object binding…
Code generation – process of converting some intermediate representation of
the source code into another computer language.
Quoted expressions ‘(single quote) will be returned as data rather than being evaluated.
For example:
'(7 a -12 ???)
is the same as:
(cons 7
(cons (quote a)
(cons -12
(cons (quote ???)
(quote ())))))
Simple lambda expression
Write a function that sums a list of numbers without using recursion
(define sum
(lambda (l)
(apply + l)))
Variadic lambda expression
A function which accepts a variable number of arguments that at execution time
collected into one list.
Write a variadic function to calculate the mean of n numbers
(define mean
(lambda x
(/ (sum x)
(length x))))
There is three binding constructs in Scheme: let, let* and letrec
In a let expression, the initial values are computed before any of the variables become
bound
(let ((x 10))
(+ x 5))
is the same as:
((lambda (x)
(+ x 5))
10)
In a let* expression, the bindings and evaluations are performed sequentially
(let* ((x 5)
(y (+ x 7)))
(+ y 3))
is the same as:
(let ((x 5))
(let ((y (+ x 7)))
(+ y 3)))
While in a letrec expression all the bindings are in effect while their initial values are
being computed, thus allowing mutually recursive definitions
(letrec ((is-even? (lambda (n)
(or (zero? n) (is-odd? (sub1 n)))))
(is-odd? (lambda (n)
(and (not (zero? n)) (is-even? (sub1 n))))))
(is-even? 12))
is the same as:
((lambda (is-even? is-odd?)
(set! is-even? (lambda (n)
(or (zero? n) (is-odd? (sub1 n)))))
(set! is-odd? (lambda (n)
(and (not (zero? n)) (is-even? (sub1 n)))))
(is-even? 12))
00)
Download