-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_calc.hs
More file actions
34 lines (26 loc) · 926 Bytes
/
stack_calc.hs
File metadata and controls
34 lines (26 loc) · 926 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
module Calculator where
newtype Calc = Calc [Int]
deriving Show
type Action a = Calc -> (Calc, a)
newtype Calculation a = CL (Action a)
pushCalc n = CL ( \(Calc lst) -> (Calc (n:lst), ()) )
popCalc = CL ( \(Calc lst) -> let x:xs = lst
in (Calc xs, x) )
addCalc = CL ( \(Calc lst) -> let a:b:xs = lst
in (Calc (a+b:xs), ()) )
instance Monad Calculation where
return x = CL (\calc -> (calc, x))
CL(c) >>= cont =
CL (\calc -> let (calc', v) = c calc
CL c' = cont v
in c' calc')
add x y = do
pushCalc x
pushCalc y
addCalc
r <- popCalc
return r
eval :: Calculation a -> Calc -> a
eval (CL f) calc = snd $ f calc
main = let calc = Calc []
in print $ eval (add 2 3) calc