Docstoc

Lecture Declarative Programming The Declarative Kernel

Document Sample
Lecture Declarative Programming The Declarative Kernel Powered By Docstoc
					                                                                                                         Lecture Outline


                                                                                                             Declarative Programming contd
                                                                                                                Dataflow Variables contd
                                                                                                                Expressions and Statements
      Lecture 5: Declarative Programming. The Declarative Kernel
                                                                                                                Functions and Procedures
                           Language Machine                                                                     Data structures

                                                                                                             The Abstract Kernel Language Machine
                                                                                                                The Semantic Stack
                                                                                                                The Single Assignment Store
                                                                                                                Operations on Variables
                                           September 8th, 2010
                                                                                                                Operations on Environments
                                                                                                                Computations

                                                                                                             Summary




                    Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (1/67)                     Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (2/67)




Dataflow Variables contd                                                                                  Dataflow Variables contd



                                                                                                             Example (Freezing)

    Unbound variables and freezing                                                                            declare X Y in
                                                                                                              Y = X + 2 % (1)
    If an unbound variable is used in an operation that needs the value of the
                                                                                                              {Browse Y} % (2)
    variable, the computation freezes.
      ◮   In the sequential model of computation it means that the whole
          execution of the program halts, as there is no way to provide the value.                           (1) The computation freezes here—neither X nor Y are bound.
      ◮   In a concurrent environment, it is just one thread that is kept waiting,                                The interpreter waits for X to become bound because its value is needed
          while other threads may provide the needed value.                                                       to compute the arithmetic operation. There is no other thread which
                                                                                                                  could do the binding, so we stop.
                                                                                                             (2) The {Browse Y} statement is never reached—there will be no output.
                                                                                                             Try it!




                    Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (3/67)                     Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (4/67)
Dataflow Variables contd                                                                                  Dataflow Variables contd



                                                                                                             Example (Browse and freezing)

                                                                                                              declare X in
    Browse again                                                                                              {Browse X}   % (1)
                                                                                                              X = 1        % (2)
    Browse introduces a new separate thread in which the browser displays a
    value.
      ◮   Browse does not belong to the declarative sequential model of                                      (1) No freezing—Browse starts a new thread in which it displays an unbound
          computation.                                                                                           variable, the thread is stopped, and the main thread proceeds.
                                                                                                             (2) X becomes bound to 1, the Browse thread is reactivated, and the output is
                                                                                                                 updated.
                                                                                                             We can visualize what happens if we introduce a delay between (1) and (2)
                                                                                                             (e.g., with the statement {Delay 2000}).1 Try it!




                                                                                                               1
                                                                                                                   Delay does not belong in the model of computation, but will often be useful for visualization.

                    Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (5/67)                           Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (6/67)




Expressions and Statements                                                                               Expressions and Statements contd



    Expressions                                                                                              Statements
    An expression is a syntactic construct which specifies an operation that                                  An statement is a syntactic construct which specifies an operation that does
    evaluates to a value.                                                                                    not evaluate to a value.

    Example (Expressions)                                                                                    Example (Statements)
      ◮   ‘2 + 2’ evaluates to 4.                                                                              ◮    ‘X=1’ unifies X with 1.
      ◮   ‘A==B’ evaluates to true or false.                                                                   ◮    ‘{Browse X+1}’ displays the value of X+1.
      ◮   ‘proc {$ X} X=1 end’ evaluates to a procedure.                                                       ◮    ‘skip’ causes the execution to proceed without any action, a
      ◮   ‘{fun {$ X} X+1 end 1}’ evaluates to the result of an application of an                                   ‘no-operation’ statement.
          anonymous function to the value 1.                                                                   ◮    ‘{proc {$} {Browse done} end}’ applies a procedure of no arguments.




                    Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (7/67)                           Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (8/67)
Expressions and Statements contd                                                                              Expressions and Statements contd

                                                                                                                  If-then-else constructs can be used as both statements and expressions,
                                                                                                                  depending on the nested instructions.
    Expressions or statements?
                                                                                                                  Example (if-statements and if-expressions)
    A program in the declarative sequential kernel language is composed                                           These two pieces of code are equivalent:
    exclusively of statements.
      ◮    But in the extended/practical language, ‘X=1’ can be used both as a                                      local X in                                                     {Browse
           statement and as an expression:                                                                             if A > B then                                                  if A > B then
                                                                                                                          X = A                                                          A
             X = 1              % valid                                                                                else                                                           else
             Y = X = 1          % likewise                                                                                X = B                                                          B
                                                                                                                       end                                                            end}
      ◮    In CTMCP, such syntactic structures are called ‘nestable constructs’                                        {Browse X}
           (App. C.2).                                                                                              end

                                                                                                                  Try it!




                        Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (9/67)                       Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (10/67)




Functions and Procedures                                                                                      Functions and Procedures contd


                                                                                                                  Example (An application of a procedure as an expression)
    Functions are linguistic abstractions over procedures.
      ◮    Any function definition and application can be translated into a                                         Procedure = proc {$ ?X} X = 1 end
           corresponding procedure definition and application.                                                      {Browse {Procedure}}
      ◮    A function of n arguments is a procedure of n + 1 arguments—a
           function’s return value is bound to an additional, implicit argument.
                                                                                                                  Example (An application of a function as a statement)
      ◮    A procedure may have more than one ‘result’ arguments.
      ◮    A function can also have more than one ‘result’ argument, but only one of                               Function = fun {$} 1 end
           them is implicit.                                                                                       local Result in
      ◮    For convenience, ‘result’ arguments may be marked with the prefix ‘?’.2                                     {Function Result}
                                                                                                                      {Browse Result}
    Since functions are a linguistic abstraction over procedures, it should be                                     end
    possible to use them interchangeably.

                                                                                                                    ◮   Cool, but we’ll try to avoid such misuse of the constructs.


      2
          This is just a syntactic convenience for the programmer, and is entirely ignored by the compiler.

                        Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (11/67)                      Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (12/67)
Functions and Procedures contd                                                                          Functions and Procedures contd

                                                                                                            Example (Factorial, a recursive function contd)
                                                                                                            We can rewrite the program in the (quasi) kernel language as follows:
    Example (Factorial, a recursive function)
                                                                                                             declare Factorial Result in
    Consider a simple recursive function that computes n! (the factorial of n):                              Factorial =
     declare                                                                                                 proc {$ N ?Result}
     Factorial =                                                                                                local Test in
     fun {$ N}                                                                                                     Test = N < 1
        if N < 2 then 1                                                                                            if Test then Result = 1
        else N * {Factorial N - 1} end                                                                             else local NestedResult NMinusOne in
     end                                                                                                              NMinusOne = N - 1
     {Browse {Factorial 10}}                                                                                          {Factorial NMinusOne NestedResult}
                                                                                                                      Result = N * NestedResult
                                                                                                                end
    This is a program in the practical language.                                                             end
                                                                                                             {Factorial 10 Result}
                                                                                                             {Browse Result}




                  Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (13/67)                      Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (14/67)




Functions and Procedures contd                                                                          Functions and Procedures contd
    And now some magic. . .
                                                                                                            Example (Magic)
                                                                                                            What does the function do?
                                                                                                             fun {Magic X Y}
                                                                                                                record(X Y)
                                                                                                             end


                                                                                                             declare X in
                                                                                                             X = {Magic 1 2}


                                                                                                             declare X Y in
                                                                                                             record(1 2) = {Magic X Y}


                                                                                                              ◮   Magic unifies its implicit result argument with a record containing X and
                                                                                                                  Y as (partial) values. The binding can go both ways. Try it!



                  Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (15/67)                      Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (16/67)
Data Structures                                                                                           Records contd
                                                                                                              Records are useful for constructing nested (recursive) data structures.
    In Oz, the most important data structure is record.
                                                                                                              Example (Representing trees with records)
      ◮   A record has a label and any number of named feature-field pairs (or
                                                                                                              This tree:
          key-value pairs, with feature=key, field=value).
      ◮   A record without any field is an atom:                                                                                                                  tree
           atom == atom()                                           % true                                                                      tree                              tree
           {Record.label atom} == atom()                            % true (!)
                                                                                                                                       leaf             leaf              tree             leaf
      ◮   Syntactically, the forms ‘ label ’ and ‘ label ()’ are not equivalent:
                                                                                                                                                                 leaf             leaf
           X = record(feature:value)                            % valid                                       can be represented with nested records as:
           X = record()(feature:value)                          % invalid
                                                                                                               Tree = tree(left:tree(left:leaf
      ◮   A record without explicit features is a tuple:                                                                             right:leaf)
                                                                                                                           right:tree(left:tree(left:leaf
           tuple(a b c) == tuple(1:a 2:b 3:c)                                 % true                                                            right:leaf)
                                                                                                                                      right:leaf))



                    Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (17/67)                     Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (18/67)




Records contd                                                                                             Records contd
    In the example above,
      ◮   a leaf node is a 0-field record (an atom) with the label leaf;
      ◮   an intermediate node is a 2-field record with the label tree, the features                           The height of a tree is the count of nodes on the longest path from the root to
          left and right, and two trees as values.                                                            a leaf.
    We can use pattern matching to perform operations on trees.                                               Example (Computing the height of a tree)
    Example (Counting leaf nodes in a tree)
                                                                                                               fun {Height Tree}
                                                                                                                  case Tree
     fun {CountLeaves Tree}
                                                                                                                  of leaf then 1
        case Tree
                                                                                                                  [] tree(left:Left right:Right) then
        of leaf then 1
                                                                                                                     {Max {Height Left} {Height Right}} + 1
        [] tree(left:Left right:Right) then
                                                                                                                  end
           {CountLeaves Left} + {CountLeaves Right}
                                                                                                               end
        end
     end


    For now we use handwaving semantics to explain pattern matching, but will
    come to a more precise explanation soon.


                    Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (19/67)                     Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (20/67)
Records contd                                                                                                   Records contd

                                                                                                                     Example (Pattern matching with #)
    The tupling constructor # is a convenient syntactic sugar for building records.                                  Instead of
        ◮    X#Y#Z is a record with the label ’#’, and three features named 1, 2, and                                 case X of record(feature:XValue) then
             3, with the fields of X, Y, and Z, respectively:                                                             case Y of record(feature:YValue) then
                                                                                                                            % use XValue and YValue
                X#Y#Z == ’#’(1:X 2:Y 3:Z)                         % true                                                 else skip
                                                                                                                         end
        ◮    When the features are consequtive integers, it is convenient to avoid                                    else skip
             typing them:                                                                                             end
                X#Y#Z == ’#’(X Y Z)                               % true
                                                                                                                     we can write
    The tupling constructor is typically used when we want to pattern-match                                           case X#Y of record(feature:XValue)#record(feature:YValue) then
    more than one variable.3                                                                                             % use XValue and YValue
                                                                                                                      else skip
                                                                                                                      end


        3
            Typically in the book. There are other ways to achieve this effect.

                          Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (21/67)                       Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (22/67)




Lists                                                                                                           Lists contd


    What is a list?
    In abstract terms, a list is an ordered collection of items.                                                     A list is a nested sequence of records.
        ◮    In Oz, lists are chains of nested records (they are single-linked lists).                                 ◮   The records that form a list have the label ’|’ and exactly two fields with
                                                                                                                           the features 1 and 2.
    Example (Lists)                                                                                                    ◮   The feature 1 of the first (topmost) record names the field which keeps
                                                                                                                           the first element of the list (the head of the list).
        [one two three]                 %   a three-element list
        [one [two three]]               %   a two-element nested list                                                  ◮   The feature 2 of the first record names a field which keeps the rest of the
        nil                             %   the empty list                                                                 list (the tail of the list).
        []                              %   not a list!                                                                ◮   The rest of the list is another list—either another record with analogous
                                                                                                                           structure, or the empty list.

    Note: ‘[]’ is used in pattern matching in the extended/practical language to
          separate alternative patterns.




                          Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (23/67)                       Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (24/67)
Lists contd                                                                                              Lists contd

                                                                                                              For most of the time, we will use syntactic sugar while talking about lists.
     Example (Lists)                                                                                          Example (Lists)
      ’|’(one nil)                         %   a list                                                          [one two]              % equivalent to ’|’(one ’|’(two nil))
      ’|’(1:one 2:nil)                     %   a list                                                          one|two|nil            % equivalent to ’|’(one ’|’(two nil))
      ’|’(2:nil 1:one)                     %   a list                                                          one|two                % not a list -- equivalent to ’|’(one two)
      ’|’(nil one)                         %   not a list (the tail is not a list)
      ’|’(nil nil)                         %   a list (the head is the empty list)
      ’|’(one ’|’(two nil))                %   a 2-element list                                               Note: Both ‘#’ and ‘|’ are used to construct records, but they are treated
      ’|’(’|’(one nil) nil)                %   a 1-element list                                                     differently:

                                                                                                               1#2#3      %   ’flat’        record:         ’#’(1        2 3)
     Note: ’|’(nil one) is the same as ’|’(1:nil 2:one) and not                                                1|2|3      %   nested        record:         ’|’(1        ’|’(2 3))
           ’|’(1:one 2:nil); since one is not a list, ’|’(nil one) is not a list                               1#2#nil    %   ’flat’        record:         ’#’(1        2 nil)
           either.                                                                                             1|2|nil    %   nested        record:         ’|’(1        ’|’(2 nil)) -- a list [1 2]




                   Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (25/67)                        Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (26/67)




Lists contd                                                                                              Lists contd

     Example (Building a list)
     We can build a list piecewise from the end towards the start:                                            A list can be seen as a tree where intermediate nodes are records with the
                                                                                                              label —.
      local A B C in
          C = nil                                                                                             Example (Lists are trees)
          B = two|C
          A = one|B                                                                                            [1 2 3] == ’|’(1 ’|’(2 ’|’(3 nil)))
          {Browse A == [one two]} % true
      end
                                                                                                                                                            ’|’
     We can also build a list piecewise from the start towards the end:
                                                                                                                                                       1          ’|’
      local A B C in
          A = one|B                                                                                                                                         2           ’|’
          B = two|C
                                                                                                                                                                 3          nil
          C = nil
          {Browse A == [one two]} % true
      end



                   Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (27/67)                        Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (28/67)
Lists contd                                                                                                               Lists contd


                                                                                                                               We can use pattern matching to access elements of a list.
     The arity of a record is a collection of all its features sorted alphanumerically.                                        Example (Appending lists)
       ◮   In Oz, the arity of a record is a list of its features, sorted.
                                                                                                                                fun {Append List1 List2}
     Example (The arity of a record as a sorted list)                                                                              case List1
                                                                                                                                   of nil then List2
      {Record.arity        record(one two three)}          %                                    [1    2    3]                      [] Head|Tail then Head|{Append Tail                                List2}
      {Record.arity        record(1:one 3:two 2:three)}    %                                    [1    2    3]                      end
      {Record.arity        record(one two:two three)}      %                                    [1    2    two]                 end
      {Record.arity        record(4:b 12:c a ’4’:d ’12’:e)}%                                    [1    4    12 ’12’ ’4’]         {Append [1 2] [3 4]} % evaluates to [1                                2 3 4]
                                                                                                                                {Append nil [3 4]}   % evaluates to [3                                4]
                                                                                                                                {Append [1 2] nil}   % evaluates to [1                                2]




                     Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (29/67)                                     Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (30/67)




Lists contd                                                                                                               Lists contd
     We can further improve our implementation of append by pattern-matching
     over both lists.
                                                                                                                               Example (Merging lists)
     Example (Appending lists contd)
                                                                                                                               Using recursion and pattern matching we can merge sorted lists into one
      fun {Append List1 List2}                                                                                                 sorted list.
         case List1#List2
                                                                                                                                fun {MergeSorted List1 List2}
         of nil#_ then List2
                                                                                                                                   case List1#List2
         [] _#nil then List1
                                                                                                                                   of nil#_ then List2
         [] (Head|Tail)#_ then Head|{Append Tail List2}
                                                                                                                                   [] _#nil then List1
         end
                                                                                                                                   [] (Head1|Tail1)#(Head2|Tail2) then
      end
                                                                                                                                      if Head1 < Head2 then Head1|{MergeSorted Tail1 List2}
                                                                                                                                      else Head2|{MergeSorted List1 Tail2} end
     Compare to how this could be done in, e.g., Erlang:                                                                           end
                                                                                                                                end
      append([],List) -> List;
      append(List,[]) -> List;
      append([Head|Tail],List) -> [Head|append(Tail,List)].



                     Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (31/67)                                     Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (32/67)
Lists contd                                                                                              Lists contd


     Mapping is a higher-order programming technique where we apply a function
     to all elements of a list. Map is a function that takes two arguments: a list and
                                                                                                              Example (Mapping)
     a one-argument function, and returns a list of the results of application of the                         We can do more tricky things with Map:
     function to every element of the input list.
                                                                                                               {Map [fun {$ X} X + 1 end
     Example (Mapping)                                                                                               fun {$ X} X * 2 end
                                                                                                                     ...]
      {Map [1 2 3] fun {$ Item} Item + 1 end}                                   % evaluates to [2 3 4]          fun {$ Function} {Function 2} end}                                % evaluates to [3 4 ...]

      {Map [1#2 2#3 3#4]
                                                                                                              Here we apply to a list of one-argument functions a function that takes a
       fun {$ Item}
                                                                                                              one-argument function as an argument and applies that function to the
          case Item of X#Y then
                                                                                                              number 2.
             if {IsOdd X} then Y else X end
          end                                                                                                   ◮   This is a typical example of functional higher-order programming (HOP).
       end}                                                                     % evaluates to [2 2 4]          ◮   Other HOP techniques include filtering, folding, accumulating, etc.
                                                                                                                ◮   More on this later.




                   Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (33/67)                       Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (34/67)




Magic?                                                                                                   Lecture Outline


                                                                                                              Declarative Programming contd
                                                                                                                 Dataflow Variables contd
         Any sufficiently advanced technology is indistinguishable from                                           Expressions and Statements
         magic.                                                                                                  Functions and Procedures
                                                                                                                 Data structures
                                                        Arthur C. Clarke
                                                                                                              The Abstract Kernel Language Machine
                                                                                                                 The Semantic Stack
         Any technology distinguishable from magic is insufficiently
                                                                                                                 The Single Assignment Store
         advanced.                                                                                               Operations on Variables
                                                                                   (author unknown)              Operations on Environments
                                                                                                                 Computations

                                                                                                              Summary




                   Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (35/67)                       Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (36/67)
The Abstract Machine                                                                                          The Abstract Machine contd

                                                                                                                  Components of the abstract machine
    So far we have                                                                                                The VM has two principal components:
      ◮    discussed (some of) the theoretical aspects of syntactic specifications of                               1. A semantic stack.
           programming languages, and
                                                                                                                   2. A single assignment store.
      ◮    used elements of this theory to specify the syntax of the declarative
           sequential kernel language (DSKL).
    We have also explained, in an intuitive, informal way, how constructs of DSKL                                                                       Abstract machine
    work when they are executed. We will now
      ◮    develop a more precise specification of the meaning of DSKL programs by                                                 Semantic stack                                 Single assignment store
           means of the DSKL Abstract Machine (or Virtual Machine, VM), and                                                     Semantic statement
      ◮    use Oz to partially implement the VM.                                                                                Semantic statement
    The VM is a model of computation4 explaining the execution of programs                                                      Semantic statement
    while hiding details of the underlying physical machine (processors, registers,                                                    ...
    memory, etc.) below a layer of abstraction.



      4
          Or is Oz itself a model of computation?

                        Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (37/67)                      Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (38/67)




The Abstract Machine contd                                                                                    The Semantic Stack


                                                                                                                  The semantic stack
                                                                                                                  The semantic stack contains semantic statements.
    To visualize computations on the VM, we will use the following notation:                                        ◮   A semantic statement is a pair composed of a (parsed) statement and an
      ◮    The VM is a pair M of the semantic stack S and the single assignment                                         environment.
           store σ:                                                                                                 ◮   The statement is a piece of program to be evaluated.
                                         M = (S, σ)                                                                 ◮   The environment is a mapping from identifiers in the code to variables in
      ◮    To show how a computation proceeds, we will illustrate it as a sequence                                      the store.
           of consequtive states of the VM:                                                                       We will use the following notation:
           Step 1: M(t1 ) = (S1 , σ1 )                                                                              ◮   The semantic stack S is a list of semantic statements:
           Step 2: M(t2 ) = (S2 , σ2 )
               ... ...                                                                                                                                            S = [s1 , s2 , . . .]
                                                                                                                    ◮   A semantic statement s is a pair of a statement and an environment:

                                                                                                                                                            si = ( statement i , Ei )




                        Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (39/67)                      Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (40/67)
The Semantic Stack contd                                                                                       The Semantic Stack contd




    Note: In CTMCP, the statements on the semantic stack are shown as pieces of
                                                                                                                   Environments
          source code.
                                                                                                                   An environment is a mapping between identifiers in statements and variables
            ◮ In practice, this would require parsing during execution, and the
                                                                                                                   in the single assignment store.
              same piece of code might need to be parse more than once (e.g.,
                                                                                                                   We will use the following notation:
              when recursion is used).
            ◮ We will follow the book’s notation in the theoretical part, but will                                   ◮    An environment E is a set of identifier-variable pairs:
              use parsed statements in our implementation.5
                                                                                                                                                          E = { id       1   → v1 , id     2   → v2 , . . .}




      5
        Our VM will take as input parse trees rather than source code; we will not develop a parser for
    DSKL at the moment.

                         Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (41/67)                           Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (42/67)




The Single Assignment Store                                                                                    The Single Assignment Store contd

    Single assignment store
    The single assignment store contains declarative variables (dataflow variables,
    variables). A number of operations on the variables in the store are allowed:
                                                                                                                   Note: A variable bound to a value will have that value until the end of the
      ◮     Creation of a new, unbound variable.                                                                         computation.7
      ◮     Binding of an unbound variable to another unbound variable.                                                    ◮ A variable bound to another variable will always have the same

      ◮     Binding of an unbound variable to a bound variable (to a value).                                                 value as that other variable.8
      ◮     Unification of two bound variables (of two values).                                                     Note: Variable names are not variables: names are elements of the code,
      ◮     Testing whether a variable is bound or not.                           6                                      variables are elements of the abstract machine.
                                                                                                                           ◮ The same identifier may map onto different variables within one
      ◮     Retrieving the value of a bound variable.
                                                                                                                              program, a variable cannot have different values during an
      ◮     Testing equivalence between two variables.                                                                        execution.
    We will use the following notation:
      ◮     The single assignment store σ is a set of variables, bound or not:

                                      σ = {v1 , v2 = 1, v3 = rec(feat : v1 ), . . .}

                                                                                                                     7
                                                                                                                         Or until it is garbage-collected—more on this later.
       6                                                                                                             8
           Testing whether a variable is bound (IsDet) is not allowed in the declarative model.                          Or both remain unbound.

                         Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (43/67)                           Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (44/67)
Operations on Variables                                                                                              Operations on Variables contd



    Creation of a variable                                                                                               Unification of unbound variables (variable-variable binding)
     ...                 % (1)
                                                                                                                          declare X Y in        % (1)
     declare X in        % (2)
                                                                                                                          X = Y                 % (2)
     ...

                                                                                                                        (1)                                                          (2)
   (1)                                                          (2)
                                                                                                                              Single assignment store                                          Single assignment store
         Single assignment store                                          Single assignment store
                                                                                                                           v1 unbound                                                    v1 unbound
                                                                    v1 unbound

                                                                                                                           v2 unbound                                                    v2 unbound




                 Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (45/67)                                  Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (46/67)




Operations on Variables contd                                                                                        Operations on Variables contd



    Binding of a variable to a value                                                                                     Binding of one of equivalent variable to a value

     declare X in                    % (1)                                                                                declare X Y in
     X = tree(leaf leaf)             % (2)                                                                                X = Y                 % (1)
                                                                                                                          X = atom              % (2)

   (1)                                                          (2)
                                                                                                                        (1)                                                          (2)
         Single assignment store                                          Single assignment store
                                                                                                                              Single assignment store                                          Single assignment store
      v1 unbound                                                    v1       bound                     tree
                                                                                                                           v1 unbound                                                    v1       bound
                                                                                                                                                                                                                            atom
                                                                                         leaf                 leaf
                                                                                                                           v2 unbound                                                    v2       bound




                 Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (47/67)                                  Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (48/67)
Operations on Variables contd                                                                                    Operations on Variables contd



    Binding of a variable to a partial value                                                                         Unification
                                                                                                                     If two complete values are of the same type and have the same structure and
     declare X Y in         % (1)                                                                                    content, unification succeeds; no additional binding is performed.
     X = record(Y)          % (2)
                                                                                                                     Example (Unification)
   (1)                                                           (2)                                                  declare X Y in
          Single assignment store                                          Single assignment store                    X = tree(leaf leaf)
                                                                                                                      Y = tree(leaf leaf)
      v1 unbound                                                     v1       bound                     record        X = Y               % (1)

      v2 unbound                                                     v2 unbound
                                                                                                                     (1) Unification succeeds, no new bindings are made.




                  Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (49/67)                                 Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (50/67)




Operations on Variables contd                                                                                    Operations on Variables contd

                                                                                                                     Unification contd
    Unification contd                                                                                                 If two (partial or complete) values do not match at some place of their
    If a partial value is unified with another (possibly partial) value, unification                                   structure, unification fails;9 Additional binding may be performed.10
    succeeds if the existing content can be unified; additional binding is
    performed as needed.                                                                                             Example (Unification contd)
    Example (Unification contd)                                                                                        declare X Y in
                                                                                                                      X = tree(leaf leaf)
     declare X Y in                                                                                                   Y = tree(leaf bird)
     X = tree(_ leaf)           % X has a nested, anonymous unbound variable                                          X = Y               % (1)
     Y = tree(leaf _)           % Y has a nested, anonymous unbound variable
     X = Y                      % (1)
                                                                                                                     (1) Both X and Y are records, their labels are identical, their features are
                                                                                                                         identical, but not all of their fields have compatible values—unification
    (1) Both X and Y are records, their labels are identical, and recursive                                              fails.
        unification of their content causes two new bindings to be made.

                                                                                                                       9
                                                                                                                         An error is raised, which we can catch as an exception—more on this later.
                                                                                                                       10
                                                                                                                         Whether additional bindings will or will not be made depends on the order in which nested
                                                                                                                     unifications are done, and is an implementational detail. See next slide.

                  Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (51/67)                                 Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (52/67)
Operations on Variables contd                                                                           Operations on Variables contd

                                                                                                            In some cases, unification failures are discovered at the run time.
    In some cases, unification failures are discovered at the compile time.                                  Example (Run-time unification failure)
    Example (Compile-time unification failure)                                                                declare X Y P in
                                                                                                             X = tree(leaf leaf)
     declare X Y in
                                                                                                             proc {P X Y}
     {Browse Y}          % (2)
                                                                                                                X = tree(worm Y) % note the order of values
     X = tree(leaf leaf)
                                                                                                             end
     X = tree(bird Y)    % (1)
                                                                                                             {Browse Y}          % (1)
                                                                                                             {P X Y}             % (2)
    (1) This statement causes a compile-time failure.
    (2) The program is actually not executed, and this statement produces no                                There is no unification failure here that would be discovered at compile time.
        output.                                                                                             (1) This statement causes Y to be displayed (as an unbound variable).
                                                                                                            (2) This statement causes a run-time unification failure; Y remains unbound
                                                                                                                and the output does not change.




                  Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (53/67)                     Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (54/67)




Operations on Variables contd                                                                           Operations on Variables contd

    In some cases, unification failures are discovered at the run time.
    Example (Run-time unification failure contd)                                                             Testing equality between variables
                                                                                                            If it can be established that two variables will always have the same value, the
     declare X Y P in                                                                                       test evaluates to true.
     X = tree(leaf leaf)
     proc {P X Y}                                                                                           Example (Testing equality between variables)
        X = tree(Y worm) % note the order of values
     end                                                                                                     declare X Y in
     {Browse Y}          % (1)                                                                               X = Y
     {P X Y}             % (2)                                                                               {Browse X == Y}          % (1)


    There is no unification failure here that would be discovered at compile time.                           (1) Because X and Y are equivalent (bound together in the store), binding
    (1) This statement causes Y to be displayed (as an unbound variable).                                       one of the to a value automatically binds the other to the same value.
                                                                                                                Therefore, true is displayed.
    (2) This statement causes a run-time unification failure, but when it occurs Y
        has already been bound to leaf and the output updated.




                  Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (55/67)                     Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (56/67)
Operations on Variables contd                                                                                 Operations on Variables contd


    Testing equality between variables contd                                                                      Testing equality between variables contd
    If it can be established that two variables will always have the same value, the                              If it can be established that two variables will never have the same value, false
    test evaluates to true.                                                                                       is returned.

    Example (Testing equality between variables contd)                                                            Example (Testing equality between variables contd)

     declare X Y in                                                                                                declare X Y in
     X = tree(leaf leaf)                                                                                           X = tree(leaf leaf)
     Y = tree(leaf leaf)                                                                                           Y = leaf
     {Browse X == Y} % (1)                                                                                         {Browse X == Y} % (1)


    (1) Because X and Y are already bound and have unifiable complete values,                                      (1) Because X and Y are already bound and their values are not unifiable,
        they will always have the same value. Therefore, true is displayed.                                           they will never have the same value. Therefore, false is displayed.




                        Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (57/67)                       Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (58/67)




Operations on Variables contd                                                                                 Operations on Environments

                                                                                                                  Operations on environments
    Testing equality between variables contd
                                                                                                                  Adjunction adds mappings creating a new, extended environment.
    If it cannot be established that two variables will always have the same value,
    and it cannot be established that they will never have the same value, the                                                                         E ′ = E + { id → v1 , . . .}
    computation suspends.11
                                                                                                                  where id stands for an identifier, and vi for a variable.
    Example (Testing equality between variables contd)
                                                                                                                    ◮   If E already contains a mapping for id , this mapping is replaced in E ′
     declare X Y in                                                                                                     with the new one.
     X = tree(leaf leaf)                                                                                                Note: In this model, environments are immutable; E does not
     Y = tree(leaf _)                                                                                                           change—operations on environments are functional.
     {Browse X == Y} % (1)
                                                                                                                  Example (Adjunction)
    (1) Because Y is bound to a partial value and it is not know what value will                                    ◮   E = {A → v1 }
        the second field of Y have, equality cannot be established and nothing is                                        E ′ = E + {B → v2 } = {A → v1 , B → v2 }
        displayed.                                                                                                  ◮   E = {A → v1 }
                                                                                                                        E ′ = E + {A → v2 } = {A → v2 }

     11
          In a concurrent environment, the thread performing the test stops.

                        Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (59/67)                       Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (60/67)
Operations on Environments contd                                                                          Operations on Environments contd

    Operations on environments contd                                                                          Operations on environments contd
    Restriction removes mappings creating a new, reduced environment:
                                                                                                              Lookup retrieves variables corresponding to specified identifiers based on the
                                                    ′
                                                  E = E|{                                                     mappings in an environment:
                                                                id , ...}

    where id stands for an identifier.                                                                                                                            v = E( id )

      ◮   E ′ contains only those mappings from E which involve identifiers from                               where id stands for an identifier, and v stands for a variable.
          the specified set.                                                                                     ◮    E( id ) returns the variable onto which id is mapped in E.
      ◮   If E does not contain a mapping for some of those identifiers, E ′ does not                            ◮    It is an error if E does not contain a mapping for id .
          contain such a mapping either.
                                                                                                              Example (Lookup)
    Example (Restriction)
                                                                                                                ◮    E = {A → v1 , B → v2 }
      ◮   E = {A → v1 , B → v2 }
                                                                                                                     E(A) = v1
          E ′ = E|{A,C} = {A → v1 }
                                                                                                                ◮    E = {A → v1 , B → v2 }
      ◮   E = {A → v1 , B → v2 }
                                                                                                                     E(C) causes a lookup error.
          E ′ = E|{} = {}



                    Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (61/67)                          Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (62/67)




Computations                                                                                              Computations contd
                                                                                                              How does a computation proceed?

    Computations                                                                                              Let statement 0 be a program.12 The abstract machine is initialized as
    A computation is a stepwise execution of a program. One step involves the                                 follows:
    following operations on the abstract machine:                                                               1. Create an empty environment:
     1. Pop the topmost semantic statement from the semantic stack.                                                                                                     E0 = {}
     2. Execute the enclosed statement using mappings in the enclosed
        environment and bindings in the single assignment store.                                               2. Create a semantic statement:

     3. Modify the semantic stack and the store as needed.                                                                                                 s0 = ( statement 0 , E0 )
     4. If the semantic stack is not empty, repeat.                                                            3. Create a semantic stack and push onto it the initial semantic statement:
                                                                                                                                                                       S0 = [s0 ]
      ◮   An empty stack means no further computation can be made—the
          execution has finished.                                                                               4. Create an empty single assignment store:
      ◮   The stack does not have to shrink—each execution step may result in                                                                                           σ0 = {}
          pushing one or more semantic statements onto the stack.
                                                                                                               5. Create the initial state of the abstract machine:
                                                                                                                                                                 M 0 = ( S0 , σ 0 )
                                                                                                               12
                                                                                                                    A program is a statement, possibly a sequence of statements—recall the grammar for DSKL.

                    Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (63/67)                          Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (64/67)
Computations contd                                                                                       Lecture Outline

    How does a computation proceed? contd
                                                                                                             Declarative Programming contd
    Start the machine in the initial execution state M0 as described above. Use the                             Dataflow Variables contd
    following algorithm:                                                                                        Expressions and Statements
                                                                                                                Functions and Procedures
     1. If in the current execution state, Mi = ( Si , σi ), the semantic stack Si is                           Data structures
        empty, stop and report success.
     2. Otherwise,
         2.1 take the first semantic statement, si 1 = ( statement i 1 , Ei 1 ), from the stack;              The Abstract Kernel Language Machine
         2.2 execute statement i 1 using, if necessary, mappings from Ei 1 and bindings                         The Semantic Stack
             from σi ;                                                                                          The Single Assignment Store
         2.3 update the state of the semantic stack from Si to Si+1 by removing the                             Operations on Variables
             topmost semantic statement (the one just executed) and pushing onto it new
                                                                                                                Operations on Environments
             semantic statements if needed;
         2.4 update the state of the single assignment store from σi to σi+1 by adding                          Computations
             new variables and performing bindings, if needed;
         2.5 in case of problems, stop and report failure.
                                                                                                             Summary
     3. Update the state of the machine from Mi to Mi+1 = ( Si+1 , σi+1 ), and
        go to 1.



                   Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (65/67)                     Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (66/67)




Summary


          This time       ◮    Dataflow variables, expressions, statements, procedures
                               and functions, data structures.
                          ◮    Operational Semantics of the Declarative Sequential
                               Kernel Language—the abstract machine.
         Next time        ◮    Step-by-step execution of statements on the abstract
                               machine.
                          ◮    Implementation of a virtual machine for a subset of
                               DSKL.
        Homework          ◮    Read Ch. 2 in CTMCP (focus on the semantic of the
                               kernel language).
                          ◮    Solve Exercise 1.
            Pensum        ◮    All of today’s slides.
        Questions?




                   Lecture 5: Declarative Programming. The Declarative Kernel Language Machine (67/67)

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:11
posted:3/22/2011
language:English
pages:17