Monads and Imperative Programming
Principles of Programming Languages
Stateful Monad
Copyright By PowCoder代写 加微信 powcoder
Evaluating binary operators before state:
deriving (Eq,Show)
type Env = [(String, Value)]
evaluate :: Exp ! Env ! Value Before state
evaluate (Literal v) env = v evaluate (Unary op a) env =
unary op (evaluate a env) evaluate (Binary op a b) env =
binary op (evaluate a env) (evaluate b env)
evaluate (If a b c) env =
let BoolV test = evaluate a env in
if test then evaluate b env else evaluate c env
evaluate (Variable x) env = fromJust (lookup x env)
evaluate (Declare x exp body) env = evaluate body new where newEnv = (x , evaluate exp env ) : env
After State
Evaluating binary operators after state:
evaluate (Binary op a b) env mem =
let (av, mem’) = evaluate a env mem in
let (bv, mem”) = evaluate b env mem’ in
(binary op av bv, mem”)
the state around makes code messy! Can we do better?
Spotting the pattern
Evaluating binary operators after errors:
evaluate (Binary op a b) env mem =
(binary op av bv, mem”)
There seems to be a repeating pattern here.
let (av, mem’) = evaluate a env mem in
let (bv, mem”) = evaluate b env mem’ in
Monads to the Rescue!
We can capture the essence of threading the state around using a Monad!
data Stateful t =
ST (Memory -> (t, Memory))
instance Monad Stateful where
return val = ST (\m -> (val, m))
(ST c) >>= f = ST (\m ->
let (val, m’) = c m
ST f’ = f val
Rewriting code
Using the do-notation for Monads we can rewrite the code as follows:
evaluate (Binary op a b) env = do
av <- evaluate a env
bv <- evaluate b env
return (binary op av bv)
Rewriting code
And here is the code for the 3 more important operations for imperative programming (see file that goes with the lecture for the full code):
evaluate (Mutable e) env = do
ev <- evaluate e env
newMemory ev
evaluate (Access a) env = do
AddressV i <- evaluate a env
readMemory i
evaluate (Assign a e) env = do
AddressV i <- evaluate a env
ev <- evaluate e env
updateMemory ev i
Monads, Functional Programming and Interpreters
Monads were introduced to Functional Programming by
See the paper below, which motivates monads through interpreters (much like the interpreters in the class)
The essence of Functional Programming, , 1992
Course Evaluation
Please go to the link:
http://setl.hku.hk
And fill out the evaluation for the course.
Course Discussion
Any comments about the course? What do you think can be improved?
What did you like or not like? Lecture style?
Tutorials?
The End :)!
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com