1 / 92

Encapsulated State

Encapsulated State. Seif Haridi Peter Van Roy. Encapsulated State. The box O. State as a group of memory cells. The box O can remember information between independent invocations, it has a memory The basic elements of explicit state Index datatypes

lane-pope
Télécharger la présentation

Encapsulated State

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Encapsulated State Seif Haridi Peter Van Roy Seif Haridi and Peter Van Roy

  2. Encapsulated State The box O State as a group of memory cells • The box O can remember information between independent invocations, it has a memory • The basic elements of explicit state • Index datatypes • Basic techniques and ideas of using state in program design An Interface that hides the state Group of functions and procedures that operate on the state Seif Haridi and Peter Van Roy

  3. Encapsulated State II The box O • What is the difference between implicit state and explicit state • What is the difference between state in general and encapsulate state • Component based programming and object-oriented programming • Abstract data types using encapsulated state State as a group of memory cells An Interface that hides the state Group of functions and procedures that operate on the state Seif Haridi and Peter Van Roy

  4. What is state? • State is a sequence of values that evolves in time that contains the intermediate results of a desired computation • Declarative programs can also have state according this definition • Consider the following program fun {Sum XsA} case Xs of X|Xr then {Sum XrA+X} [] nil then A end end {Show {Sum [1 2 3 4] 0}} Seif Haridi and Peter Van Roy

  5. What is implicit state? The two arguments Xs and A represents an implicit state Xs A [1 2 3 4] 0 [2 3 4] 1 [3 4] 3 [4] 6 nil 10 fun {Sum XsA} case Xs of X|Xr then {Sum XrA+X} [] nil then A end end {Show {Sum [1 2 3 4] 0}} Seif Haridi and Peter Van Roy

  6. What is explicit state: Example? an unbound variable X C A cell C is created with initial value 5 X is bound to C 5 X C The cell C, X is bound to, is assigned the value 6 6 X Seif Haridi and Peter Van Roy

  7. What is explicit state: Example? an unbound variable X • The cell is a value container with a unique identity • X is really bound to the identity of the cell • When the cell is assigned, X do not • change C A cell C is created with initialvalue 5 X is bound to C 5 X C The cell C, X is bound to, is assigned the value 6 6 X Seif Haridi and Peter Van Roy

  8. What is explicit state? • X = {NewCell I} • Creates a cell with initial value I • Binds X to the identity of the cell • Example: X = {NewCell 0} • {Assign +X J} • Assumes X is bound to a cell C (otherwise exception) • Changes the content of C to become J • Y = {Access +X} • Assumes X is bound to a cell C (otherwise exception) • Binds Y to the value contained in C Seif Haridi and Peter Van Roy

  9. Examples 0 X • X = {NewCell 0} • {Assign X 5} • Y = X • {Assign Y 10} • {Access X} == 10 % returns true • X == Y% returns true 5 X Y 10 X Y Seif Haridi and Peter Van Roy

  10. Examples 10 X • X = {NewCell 10}Y = {NewCell 10} • X == Y% returns false • Because X and Y refer to different cells, with different identities • {Access X} == {Access Y}returns true 10 Y Seif Haridi and Peter Van Roy

  11. Examples 0 X • X = {NewCell 0} • {Assign X 5} • Y = X • {Assign Y 10} • X == 10returns true 5 X Y 10 X Y Seif Haridi and Peter Van Roy

  12. The model extented with cells Semantic stack (Thread 1) Semantic stack (Thread n) ..... w= f(x) z = person(a:y) y = 1 u = 2 x 1: w 2: x .... .... single assignment store mutable store Seif Haridi and Peter Van Roy

  13. The stateful model s::= skip empty statement|s1s2statement sequence | ... |threads1 end thread creation|{NewCellxc}cell creation |{Exchange cx y} cell exchange Unify (bind) xto the old value of cand set the content of the cell cto y Seif Haridi and Peter Van Roy

  14. The stateful model |{NewCellxc}cell creation |{Exchange cx y} cell exchange Unify (bind) xto the old value of cand set the content of the cell cto y proc {Assign C X} {Exchange C _ X} end fun {Access C} X in{Exchange C X X}X end Seif Haridi and Peter Van Roy

  15. Do we need explicit state? • Up to now the computation model we introduced in the previous lectures did not have any notion of explicit state • And important question is: do we need explicit state? • There is a number of reasons for introducing state, we discuss them some of them here Seif Haridi and Peter Van Roy

  16. Modular programs • A system (program) is modular if changes (updates) in the program are confined to the components where the functionality are changed • Here is an example where introduction of explicit state in a well confined way leads to program modularity compared to programs that are written using only the declarative model (where evey component is a function) Seif Haridi and Peter Van Roy

  17. Encapsulated state I fun {MF} fun {F ...} Definition of F endfun {G ...} Definition of G end in ’export’(f:F g:G) end M = {MF} • Assume we have three persons, P, U1 and U2 • P is a programmer that developed a component M that provides two functions F and G • U1 and U2 are system builders that use the component M Seif Haridi and Peter Van Roy

  18. Encapsulated state I • Assume we have three persons, P, U1 and U2 • P is a programmer that developed a component M the provides two functions F and G • U1 and U2 are system builders that use the component M functor MF export f:F g:G define fun {F ...} Definition of F end fun {G ...} Definition of G end end Seif Haridi and Peter Van Roy

  19. Encapsulated state II • User U2 has a demanding application • He wants to extend the module M to enable him to monitor how many times the function F is invoked in his application • He goes to P, and asks him to do so without changing the interface to M fun {M} fun {F ...} Definition of F endfun {G ...} Definition of G end in ’export’(f:F g:G) end Seif Haridi and Peter Van Roy

  20. Encapsulated state III • This cannot be done in the declarative model because F cannot remember its previous invocations • The only way to do it there is to change the interface to F by adding two extra arguments FIn and FOut fun {F ... +FIn ?FOut} FOut = FIn+1 ...end • The rest of the program always remembers the previous number of invocations (FIn), and FOut retruns the new number of invocation • But this changes the interface! Seif Haridi and Peter Van Roy

  21. Encapsulated state III fun {MF} X = {NewCell 0} fun {F ...} {Assign X {Access X}+1} Definition of F endfun {G ...} Definition of G end fun {Count} {Access X} end in ’export’(f:F g:G c:Count) end M = {MF} • A cell is created when MF is called • Due to lexical scoping the cell is only visible to the created version of F and Count • The M.f did not change • New function M.c is available • X is hidden only visible inside M (encapsulated state) Seif Haridi and Peter Van Roy

  22. Relationship between the declarative model and the stateful model • Declarative programming guarantees by construction that each procedure computes a function • This means each component (and subcomponent) is a function • It is possible to use encapsulated state (cells) so that a component is declarative from outside, and stateful from the inside • Considered as a black-box the program procedure is still a function Seif Haridi and Peter Van Roy

  23. Programs with accumulators local fun {Sum1 Xs A} case Xs of X|Xr then {Sum1 Xr A+X} [] nil then A endend in fun {Sum Xs} {Sum1 Xs 0} end Seif Haridi and Peter Van Roy

  24. Programs with accumulators fun {Sum Xs} fun {Sum1 Xs} case Xs of X|Xr then{Assign A X+{Access A}}{Sum1 Xr} [] nil then{Access A} endendA = {NewCell 0} in {Sum1 Xs} end fun {Sum Xs} fun {Sum1 Xs A} case Xs of X|Xr then {Sum1 Xr A+X} [] nil thenA endend in {Sum1 Xs 0} end Seif Haridi and Peter Van Roy

  25. Programs with accumulators fun {Sum Xs} fun {Sum1 Xs} case Xs of X|Xr then{Assign A X+{Access A}}{Sum1 Xr} [] nil then{Access A} endendA = {NewCell 0} in {Sum1 Xs} end fun {Sum Xs} A = {NewCell 0} in {ForAll Xs proc {$ X} {Assign A X+{Access A}} end}{Access A} end Seif Haridi and Peter Van Roy

  26. Programs with accumulators fun {Sum Xs} A = {NewCell 0} in {ForAll Xs proc {$ X} {Assign A X+{Access A}} end}{Access A} end fun {Sum Xs} A = {NewCell 0} in for X in Xs do {Assign A X+{Access A}} end{Access A} end The state is encapsulated inside each procedure invocation Seif Haridi and Peter Van Roy

  27. Indexed Collections • Indexed collections groups a set of (partial) values • The individual elements are accessible through an index • The declarative model provides: • tuples, e.g. date(17 december 2001) • records, e.g. date(day:17 month:decemeber year:2001) • We can now add state to the fields • arrays • dictionaries Seif Haridi and Peter Van Roy

  28. Arrays • An array is a mapping from integers to (partial) values • The domain is a set of consecutive integers, with a lower bound and an upper bound • The range can be mutated (change) • A good approximation is to thing of arrays as a tuple of cells Seif Haridi and Peter Van Roy

  29. Operations on arrays • A = {Array.new LBUB?Value} • Creates an array A with lower bound LB and upper bound UB • All elements are initialized to Value • There are other operations: • To access and update the elements of the array • Get the lower and upper bounds • Convert an array to tuple and vice versa • Check its type Seif Haridi and Peter Van Roy

  30. Example 1 fun {MakeArray L H F} A = {Array.new L H unit} in for I in L..H do A.I := {F I} end A end • A = {MakeArray L H F} • Creates an array A where for each index I is mapped to {F I} Seif Haridi and Peter Van Roy

  31. Array2Record • R = {Array2Record L A} • Define a function that takes a label L and an array A, it returns a record R whose label is L and whose features are from the lower bound of A to the upper bound of A • We need to know how to make a record • R = {Record.make L Fs} • creates a record R with label L and a list of features (selector names), returns a record with distict fresh variables as values • L = {Array.low A} and H = {Array.high A} • Return lower bound and higher bound of array A Seif Haridi and Peter Van Roy

  32. Array2Record fun {Array2Record LA A} L = {Array.low A} H = {Array.high A} R = {Record.make LA {From L H}} in for I in L..H do R.I = A.I end R end Seif Haridi and Peter Van Roy

  33. Tuple to Array fun {Tuple2Array T} H = {Width T} in {MakeArray 1 H fun{$ I} T.I end} end Seif Haridi and Peter Van Roy

  34. Dictionaries (Hash tables) • A dictionary is a mapping from simple values or literals (integers, atoms, amd names) to (partial) values • Both the domain and the range can be mutated (changed) • The pair consisting of the literal and the value is called an item • Items can be added, changed and removed in amortized constant time • That is to say n operations takes on average O(n) Seif Haridi and Peter Van Roy

  35. Operations on dictionaries • D = {Dictionary.new} • Creates an empty dictionary • There are other operations: • To access and update (and add) the elements of a dictionary using the ’.’ and ’:=’ notations • Remove an item, test the memership of a key • Convert a dictionary to a record and vice versa • Check its type Seif Haridi and Peter Van Roy

  36. Indexed Collections stateless collection Tuple Add state Add atoms as indices stateful collection Array Record Add atoms as indices Add state Dictionary Seif Haridi and Peter Van Roy

  37. Other collections stateless collection lists potentially infinite lists ports streams stateful collection generalizes streams to stateful mailboxes stacks queues stateless Seif Haridi and Peter Van Roy

  38. Encapsulated stateful abstract datatypes ADT • These are stateful entities that can be access only by the external interface • The implementation is not visible outside • The are two method to build statefull abstract data types • The functor based approach (record interface) • The procedure dispatch approach Seif Haridi and Peter Van Roy

  39. The functor-based approach fun {NewCounter I} S = {Record.toDictionary state(v:I)} proc {Inc}S.v := S.v + 1end proc {Dec}S.v := S.v – 1end fun {Get} S.v end proc {Put I} S.v := I end proc {Display} {Show S.v} end ino(inc:Incdec:Decget:Getput:Putshow:Display) end Seif Haridi and Peter Van Roy

  40. The functor-based approach fun {NewCounter I} S = {Record.toDictionary state(v:I)} proc {Inc}S.v := S.v + 1end proc {Dec}S.v := S.v – 1end fun {Get} S.v end proc {Put I} S.v := I end proc {Display} {Show S.v} end ino(inc:Incdec:Decget:Getput:Putshow:Display) end The state is collected in dictionary S The state is completely encapsulated i.e. not visible out side Seif Haridi and Peter Van Roy

  41. The functor-based approach fun {NewCounter I} S = {Record.toDictionary state(v:I)} proc {Inc}S.v := S.v + 1end proc {Dec}S.v := S.v – 1end fun {Get} S.v end proc {Put I} S.v := I end proc {Display} {Show S.v} end ino(inc:Incdec:Decget:Getput:Putshow:Display) end The interface is created for each instance Counter Seif Haridi and Peter Van Roy

  42. The functor-based approach fun {NewCounter I} S = {Record.toDictionary state(v:I)} proc {Inc}S.v := S.v + 1end proc {Dec}S.v := S.v – 1end fun {Get} S.v end proc {Put I} S.v := I end proc {Display} {Show S.v} end ino(inc:Incdec:Decget:Getput:Putshow:Display) end function that access the state by lexical scope Seif Haridi and Peter Van Roy

  43. Call pattern declare C1 C2 C1 = {NewCounter 0} C2 = {NewCounter 100} {C1.inc} {C1.show} {C2.dec} {C2.show} Seif Haridi and Peter Van Roy

  44. Defined as a functor functor Counter export inc:Incdec:Decget:Getput:Putshow:Display init:Init define S proc {Init init(I)} S = {Record.toDictionary state(v:I)}end proc {Inc}S.v := S.v + 1end proc {Dec}S.v := S.v – 1end fun {Get} S.v end proc {Put I} S.v := I end proc {Display} {Show S.v} end end Seif Haridi and Peter Van Roy

  45. Functors • Functors have been used as a specification of modules • Also functors have been used as a specification of abstract datatypes • How to create a stateful entity from a functor? Seif Haridi and Peter Van Roy

  46. Explicit creation of objects from functors • Given a variable F that is bound to a functor • [O] = {Module.apply [F]}creates stateful ADT object O that is an instance of F • Given the functor F is stored on a file ’f.ozf’ • [O] = {Module.link [’f.ozf]}creates stateful ADT object O that is an instance of F Seif Haridi and Peter Van Roy

  47. Defined as a functor functor Counter export inc:Incdec:Decget:Getput:Putshow:Display init:Init define S proc {Init init(I)} S = {Record.toDictionary state(v:I)}end proc {Inc}S.v := S.v + 1end proc {Dec}S.v := S.v – 1end fun {Get} S.v end proc {Put I} S.v := I end proc {Display} {Show S.v} end end Seif Haridi and Peter Van Roy

  48. Pattern of use fun {New Functor Init} [M] = {Module.apply [Functor]} {M.init Init} M end declare C1 C2 C1 = {New Counter init(0)} {C1.inc} {C1.show} {C2.inc} {C2.show} Seif Haridi and Peter Van Roy

  49. Example:memoization • Stateful programming can be used to speed up declarative (functional) components by remembering previous results • Consider the pascal triangle • One way to make it faster between separate invocations is to remember previously computed rows • Here follow our principle an change only the interna of a component Seif Haridi and Peter Van Roy

  50. Functions over lists 1 • Compute the function {Pascal N} • Takes an integer N, and returns the Nth row of a Pascal triangle as a list • For row 1, the result is [1] • For row N, shift to left row N-1 and shift to the right row N-1 • Align and add the shifted rows element-wise to get row N 1 1 1 2 1 (0) 1 3 3 1 (0) 1 4 6 4 1 Shift right [0 1 3 3 1] [1 3 3 1 0] Shift left Seif Haridi and Peter Van Roy

More Related