Docstoc

Functional programming

Document Sample
Functional programming Powered By Docstoc
					440 Midterm 1, 2007




                      1
• (1 point) Which of the following is not an OO
   programming language?
   – Java
   – C++
   – Smalltalk
   – Simula 67
   – None of the above.




                                                  2
•   (1 point) Which of the following language is not a declarative language?
    –   Java
    –   Prolog
    –   SQL
    –   Scheme
    –   None of the above.


•   Imperative: a programming paradigm that describes computation in terms
    of a program state and statements that change the program state.
•   A program is "declarative" if it describes what something is, rather than
    how to create it.
    –   Imperative programs make the algorithm explicit and leave the goal implicit;
    –   Declarative programs make the goal explicit and leave the algorithm implicit.

•   Examples of declarative languages:
    –   Functional programming languages, Logic programming languages, SQL.


                                                                                        3
• (1 point) Which of the following is a script language?
   – Java
   – C#
   – PHP
   – Prolog
   – Scheme
   – None of the above.

• Scripting: connecting diverse pre-existing components
   to accomplish a new related task.
   – Favor rapid development over efficiency of execution;
   – Often implemented with interpreters rather than compilers;
   – Strong at communication with program components written in
     other languages.

                                                                  4
• (1 point) BNF was first used to describe the syntax of
    which language:
    – C
    – Fortran
    – Algol
    – COBOL
    – LISP
    – None of the above

•




                                                           5
ALGOL (ALGOrithmic Language)

  • de facto standard way to report algorithms in print
  • Designed to improve Fortran
  • John Backus developed the Backus Normal/Naur Form method of describing
    programming languages.
  • ALGOL 60 inspired many languages that followed it
       "ALGOL 60 was a great improvement on its successors.“
       The full quote is "Here is a language so far ahead of its time, that it was not only an improvement
         on its predecessors, but also on nearly all its successors" --C. A. R Hoare

       procedure Absmax(a) Size:(n, m) Result:(y) Subscripts:(i, k);
        value n, m; array a; integer n, m, i, k; real y;
        comment The absolute greatest element of the matrix a, of size n by m is transferred to y, and the subscripts of
          this element to i and k;
       begin integer p, q;
          y := 0; i := k := 1;
          for p:=1 step 1 until n do
          for q:=1 step 1 until m do
              if abs(a[p, q]) > y then
                begin y := abs(a[p, q]);
                         i := p; k := q
                end
         end Absmax




                                                                                                                   6
• ( 1 point) Which of the following is not part of a
   compiler?
   – Scanner;
   – Parser;
   – Code generator;
   – Optimizer;
   – Interpreter;
   – None of the above.




                                                       7
                                           Source program         Compilation and execution
                                                                                                      compiler
Classification by implementation methods




                                           Lexical Analysis      Token Sequence              Syntactic Analysis
                                             (scanning)                                          (parsing)
                                                                   Symbol Table
                                                                                                 Parse Tree

                                               Code              Abstract Program               Semantic
                                            Optimization        (Intermediate code)             Analysis

                                           Abstract Program
                                             (Optimized)

                                              Code               Object Program               Loader / Linker
                                            Generation            (Native Code)

                                                                                              Target Program
                                                Input Data    Computer         Output Data


                                                                                                                  8
•   (1 point) When you run the following Java program:
    public class Hello {
    public static void main(String [ ] a){
    System.out.println("Hello");
    }
    }

•   How many classes will be loaded into the system?
    –   One
    –   Two
    –   Three
    –   Dozens
    –   Hundreds
    –   None of the above

                                                         9
                                                                                       public class Hello {
Run java -verbose                                                                      public static void main(String [] a){
                                                                                        System.out.println("Hello");
sol:~/440>java -verbose Hello
                                                                                       }
[Opened /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
                                                                                       }
[Opened /usr/jdk/instances/jdk1.5.0/jre/lib/jsse.jar]
[Opened /usr/jdk/instances/jdk1.5.0/jre/lib/jce.jar]
[Opened /usr/jdk/instances/jdk1.5.0/jre/lib/charsets.jar]
[Loaded java.lang.Object from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
[Loaded java.io.Serializable from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
[Loaded java.lang.Comparable from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
[Loaded java.lang.CharSequence from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
[Loaded java.lang.String from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
[Loaded java.lang.reflect.GenericDeclaration from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
[Loaded java.lang.reflect.Type from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
[Loaded java.lang.reflect.AnnotatedElement from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
[Loaded java.lang.Class from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
[Loaded java.lang.Cloneable from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
[Loaded java.lang.ClassLoader from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
[Loaded java.lang.System from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
… (hundreds of related classes)
[Loaded Hello from file:/global/fac2/jlu/440/]
Hello
[Loaded java.lang.Shutdown from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]
[Loaded java.lang.Shutdown$Lock from /usr/jdk/instances/jdk1.5.0/jre/lib/rt.jar]




                                                                                                                               10
• ( 1 point) A program written in an interpreted language
   is usually
   – slow to run;
   – slow to develop;
   – slow to compile;
   – None of the above.




                                                        11
                                           Interpreted language
                                            • Programs are executed from source form, by an
Classification by implementation methods




                                              interpreter.
                                                – many languages have both compilers and interpreters,
                                                  including Lisp, BASIC, and Python.

                                            • Disadvantages:
                                                – Much slower
                                                     – Real time translation;
                                                     – Initially, interpreted languages were compiled line-by-line; each line
                                                       was compiled as it was about to be executed, and if a loop or
                                                       subroutine caused certain lines to be executed multiple times, they
                                                       would be recompiled every time.
                                                – Require more space.
                                                     – Source code, symbol table, …

                                            • Advantage of interpreted languages
                                                – Easy implementation of source-level debugging operations,
                                                  because run-time errors can refer to source-level units
                                                     – E.g., if an array index is out of range, the error message can easily
                                                       indicate the source line and the name of the array.
                                                – It can take less time to interpret it than the total time required
                                                  to compile and run it. This is especially important when
                                                  prototyping and testing code when an edit-interpret-debug
                                                  cycle can often be much shorter than an edit-compile-run-
                                                  debug cycle. (e.g., csh)


                                                                                                                                12
• (1 point) Compared with declarative languages, which
    of the following is not true for imperative languages:
    – Can have side effects;
    – More efficient to run;
    – Closer to computer;
    – Hard to implement;
    – None of the above.

•




                                                             13
Why is it difficult to implement declarative languages?
 • By definition, it specifies what the task is, not the way how to solve
   it.
 • Consider the following query:
     – customers(id, name, phone)
     – Orders(o-id, c-id, product, price, date)
     SELECT product, price, date
     FROM customers, orders
     WHERE customers.id = orders.c-id AND customers.name=“john”

 • It declares what we want. Does not specify how to implement it.
     – e.g. which condition to run first?
 • There are many different ways to implement.
     – A naïve one would be very expensive (construct the Cartesian product
       of the two tables, join two ids first) would be very expensive;
 • Query engine (compiler) will take care of these implementation
   issue.
 • Conclusions:
     – Declarative programming focus on higher level of abstraction;
     – It is more difficult to implement.


                                                                            14
• (1 point) Given the expression ((x.xx)(x.x))a in
    lambda calculus. Derive the expression as far as
    possible using β-reduction. The final result will be:
    – (x.x)a
    – x.x
    – xa
    – a
    – none above

•




                                                            15
• (1 point) Which of the following is a correct rule for the
   if statement?
   –        {P} S {Q}                  {P} S {Q} B  Q
       {P} if B then S {Q}             {P} if B then S {Q}

        {P} S {Q} B  Q                {P  B} S {Q}
         {P} if B then S {Q}
                                       {P} if B then S {Q}




                                                             16
1. Which of the following is a rule that is correct for the
   while statement?

        {P} S {Q}                      {P} S {P} P  Q
   {P} while B do S {Q}               {P} while B do S {Q}



         {P } S {P}               {P  B} S {P}      P  B  Q
 {P} while B do S {P  B}             {P} while B do S {Q}




                                                              17
• (1 point) What is the value of (map (lambda (x) (* 2 x))
   (1 2 3)) ?
   – a run-time error
   –   ( ) (the empty list)
   – (3 4 5)
   – (2 4 6)
   – 12
   – none of the above




                                                        18
• (1 point) What is the value of (map (lambda (x) (* 2 x))
    '(1 2 3)) ?
    – a run-time error
    –   ( ) (the empty list)
    – (3 4 5)
    – (2 4 6)
    – 12
    – none of the above

•




                                                        19
•   (1 point) What is the value of (eval (map (lambda (x) (* 2 x)) '(1 2 3)))?
    –   a run-time error
    –    ( ) (the empty list)
    –   (3 4 5)
    –   (2 4 6)
    –   12
    –   none of above

•   Forced evaluation
    (+ 1 2 3)                   => 6
    '(+ 1 2 3)                  => (+ 1 2 3)
    (eval '(+ 1 2 3))           => 6


•   eval evaluates its single argument
•   eval is implicitly called by the interpreter to evaluate each expression
    entered:


                                                                               20
• Imperative languages are very high level programming
   languages.




                                        Very high
                                        level
                                        Language
                           High Level
                           Language
                Assembly
                Language
     Machine
     Language

                           Languages                though
 machine
                                                       t
                                                             Closer to humans
                                                                      21
• Declarative languages are more difficult to implement
   than imperative languages.




                                                          22
Declarative programming example: SQL
• Consider the following query:                           id                  name                phone
    – customers(id, name, phone)
    – Orders(o-id, c-id, product, price, date)            123                 Mike                2533000
                                                          124                 john                2345678
    SELECT product, price, date
    FROM customers, orders                                125                 Vivian              123 4567
    WHERE customers.id = orders.c-id AND
     customers.name=“john”                           O-id        C-id      product         price          Date
• It declares what we want. Does not specify         01          123       Coke            1.00           06-01-11
  how to implement it.
    – e.g. which condition to run first?             02          124       water           6              06-01-02
• There are many different ways to                   03          123       juice           4              06-01-03
  implement.
    – A naïve one would be very expensive            04          125       milk            3.8            06-01-01
      (construct the Cartesian product of the two
      tables, join two ids first) would be very
      expensive;                                    id    name     Phone          O-id   C-id     Product    price   date

• Query engine (compiler) will take care of         123   Mike     2533000        01     123      Coke               ..

  these implementation issue.                       123   Mike     2533000        03     123      Juice              ..

                                                    124   john     2345678        02     124      Water              ..
• Conclusions:                                      125   Vivian   123 4567       04     125      Wilk               ..
    – Declarative programming focus on higher
      level of abstraction;
    – It is more difficult to implement.


                                                                                                             23
Although Fortran is the first high level programming
    language, it is still used in areas such as engineering.
1955
       Fortran I                                                                        Lisp
       Fortran II             Algol 58
1960                          Algol 60        Cobol
       Fortran IV
                                                      Simula I
1965                  Basic                    PL/I
                                                      Simula 67
                              Algol 68
1970
                                     Pascal      C                                               Prolog
1975
       Fortran 77                 Modula-2                                           Scheme
                                                                                ML
1980                                                             Smalltalk 80

                                               Ada                               Common
1985                                                   C++

                      QuickBasic Oberon
1990 Fortran 90       Visual Basic
                                                                                     Haskell
                                                           Delphi                              Goedel
1995                                                   Ada95      Java                            Mercury
                                                                                CAML

2000                                                                C#
       Fortran 2003

2005
                                                                                                     24
A compiler can translate source code of one high level
    language to another high level language.
 • Compilation: translating high-level program (source
   language) into machine code (machine language)
    – Slow translation, fast execution



 • High level to high level language translation:
   programming language transformation




                                                         25
Functional programming language was invented later than
   high level programming languages such as Algol.
1955
       Fortran I                                                                        Lisp
       Fortran II             Algol 58
1960                          Algol 60        Cobol
       Fortran IV
                                                      Simula I
1965                  Basic                    PL/I
                                                      Simula 67
                              Algol 68
1970
                                     Pascal      C                                               Prolog
1975
       Fortran 77                 Modula-2                                           Scheme
                                                                                ML
1980                                                             Smalltalk 80

                                               Ada                               Common
1985                                                   C++

                      QuickBasic Oberon
1990 Fortran 90       Visual Basic
                                                                                     Haskell
                                                           Delphi                              Goedel
1995                                                   Ada95      Java                            Mercury
                                                                                CAML

2000                                                                C#
       Fortran 2003

2005
                                                                                                     26
Modern high level programming languages removed
   GOTO statement, hence they can’t describe some
   computational tasks that could have been
   described using GOTO statement.




                                                27
                                  Structured programming
Classification by programming paradigms



                                          • Any program can be goto-free (1966, Böhm and Jacopini,
                                           CACM)
                                             – any program with gotos could be transformed into a goto-free form
                                               involving only
                                                – Sequential composition
                                                – choice (IF THEN ELSE) and
                                                – loops (WHILE condition DO xxx),
                                                – possibly with duplicated code and/or the addition of Boolean variables
                                                  (true/false flags).


                                                                           Y C       N
                                                                                                         Y C      N
                                             S1        S2               S1           S2
                                                                                                        S

                                                                                                                    28
If we can prove the Hoare triple {P} S {Q}, we can say
    that program S is totally correct for the pre-
    condition P and pos-condition Q.


 • {P} S {Q} means “if we assume that P holds before S
   starts executing, then Q holds at the end of the execution
   of S”
    – I.e., if we assume P before execution of S, Q is guaranteed after
      execution of S

 • To prove total correctness we also have to prove that the
   loop terminates




                                                                     29
Java supports higher order function.

 • Example of higher order function:
    (map + '(1 2 3) '(4 5 6))




                                       30
• Given the following Hoare triple
   {true}
     x := 0; f := 1;
     while ( x < n ) do (x := x + 1; f := f * x;)
   {f=n!}

• Write its loop invariant.
   f=x!
   ∧ x<=n




                                                    31
• Write the result of running the following Scheme
   program.
   (define (f lst)
       (if (null? lst)
          0
          (+ (f (cdr lst)) (car lst))))
   (f '(1 2 3))




                                                     32

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:4
posted:7/22/2012
language:
pages:32