Lec15.5 - Adding set and seq to a haskell interpreter of mutation PDF

Title Lec15.5 - Adding set and seq to a haskell interpreter of mutation
Author Simon Fraser
Course Elem Alg Des and Data Abst Adv
Institution University of Waterloo
Pages 2
File Size 25 KB
File Type PDF
Total Downloads 35
Total Views 124

Summary

Adding set and seq to a haskell interpreter of mutation...


Description

Let's add set (for mutation) and seq (for sequencing). exp = ... | (set id exp) | (seq exp exp) data Ast = ... | Set String Ast | Seq Ast Ast Note: we will implement mutation without using mutation. Implementing set - basic idea - change the name-value binding in env. Needs to be done carefully. Consider (with ((x 0)) (+ (seq (set x 5) x) (seq (set x 6) x))). Should produce 11. (set x 6) changes the environment so that x maps to 6. Use that environment when evaluating all that follows. But what about (with ((x 0)) (+ (seq (set x 5) x) (seq (with ((x 10)) 0) x)))? It should produce 10. Careful about returning environments! Don't want 15. So each expr should return the env. that results after it is finished, so that the updated environment can be used in what follows. Can this model - threading environments in and out of exprs work? Yes, if you do it right. Boxes - Need a model that permits aliasing. Idea (recall): Env. maps variables to locations. Not threaded, never updated, only added to. The store maps locations to values. Values are updated, but locations are not. Aliasing - two or more vars map to same location. interp takes a store as an add. param. Returns an updated store as a result. interp :: Ast->Env->Store->(Val, Store) -- returns a val, store pair. type Loc = Integer type Env = [(String, Loc)] type Store = [(Loc, Val)] interp interp interp s'' as

(Number v) _ s = (Numb v, s) -- have to return store (Fun p b) e s = (Closure p b e, s) (Bin op x y) e s = (Numb (opTrans op v w), s'') -- give back store. where (Numb v, s') = interp x e s -- as it prod. a val, store pair (Numb w, s'') = interp y e s' -- have to do this in store s' interp (Seq x y) e s = (v, s'') where (_, s') = interp x e s -- can use _ to denote anything

(v, s'') = interp y e s' -- can use v to denote any value interp (Var x) e s = (fromMaybe undefined (lookup loc s), s) where loc = fromMaybe undefined (lookup x e) -- x may be undefined interp (App f x) e s = interp fb ne ns where (Closure fp fb fe, s') = interp f e s (y, s'') = interp x e s' nl = newloc s'' -- newloc is just a fn producing a new loc ne = (fp, nl):fe -- e is a var->loc mapping ns = (nl, y):s'' -- s is a loc->val mapping interp (Set x y) e s = (void, ns) where lx = fromMaybe undefined (lookup x e) (nv, s') = interp y e s ns = (lx, nv):s' newloc store. better End of

= length - works because we never remove a location from the Impractical for long computations. - reuse old location ("garbage collection" - maybe later) module 1....


Similar Free PDFs