Skip to content

Commit 5ec73bc

Browse files
committed
stacks
1 parent cb683c4 commit 5ec73bc

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import Control.Monad (when)
2+
import Control.Monad.State
3+
4+
type Stack = [Int]
5+
6+
pop :: State Stack Int
7+
pop = state $ \(x:xs) -> (x, xs)
8+
9+
push :: Int -> State Stack ()
10+
push a = state $ \xs -> ((), a : xs)
11+
12+
-- try:
13+
-- runState stackManip [5,8,2,1]
14+
stackManip :: State Stack Int
15+
stackManip = do
16+
push 3
17+
pop
18+
pop
19+
20+
-- try:
21+
-- runState stackStuff [9,0,2,1,0]
22+
stackStuff :: State Stack ()
23+
stackStuff = do
24+
a <- pop
25+
if a == 5
26+
then push 5
27+
else do
28+
push 3
29+
push 8
30+
31+
-- try:
32+
-- runState moreStack [100,0,2,1,0]
33+
moreStack :: State Stack ()
34+
moreStack = do
35+
a <- stackManip
36+
when (a == 100) stackStuff
37+
38+
-- try:
39+
-- runState stackyStack [1,2,3]
40+
stackyStack :: State Stack ()
41+
stackyStack = do
42+
stackNow <- get
43+
if stackNow == [1, 2, 3]
44+
then put [8, 3, 1]
45+
else put [9, 2, 1]

0 commit comments

Comments
 (0)