-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack6.hs
83 lines (75 loc) · 1.91 KB
/
stack6.hs
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
-- Stack
newtype Stack a = Stack [a] deriving Show
type StackOp b a = Stack a -> (b, Stack a)
-- Stackの先頭に要素を追加
-- (追加する要素) -> (初期Stack) -> (先端の要素, 更新されたStack)
push :: a -> StackOp a a
push c (Stack cs) = (c, Stack (c:cs))
-- Stackの専用の要素を取り出す
-- (初期Stack) -> (取り出された要素, 更新されたStack)
pop :: StackOp a a
pop (Stack (c:cs)) = (c, Stack cs)
-- popした要素を調べる
headIs :: (a -> Bool) -> Stack a -> (Bool, Stack a)
headIs checker s = (i', s')
where
(i, s') = pop s
i' = checker i
-- 空にする
empty :: Stack a -> ((), Stack a)
empty _ = (i, s)
where
i = ()
s = Stack []
-- なにもしない
unit :: b -> StackOp b a
unit i cs = (i, cs)
-- method -> (lambda ) -> (stack -> (i' , s' ))
bind :: StackOp b a -> (b -> StackOp c a) -> StackOp c a
bind method lambda = \stack ->
let
(i, s) = method stack
(i', s') = lambda i s
in
(i', s')
-- 結果を必要としないbind (結果が必要ないので第2引数はlambda式の戻り値だけ)
bind_ :: StackOp b a -> StackOp c a -> StackOp c a
bind_ method inLambda = method `bind` \_ -> inLambda
main = do
let stack = Stack [1, 2, 3, 4, 5]
print
$ (headIs (> 4)
`bind` \i1 -> headIs (> 3)
`bind` \i2 -> headIs (> 2)
`bind` \i3 -> unit $ and [i1, i2, i3])
$ stack
print
$ (pop
`bind` \i1 -> pop
`bind` \i2 -> unit $ i1 + i2)
$ stack
print
$ (push 10
`bind_` push 12
`bind_` pop
`bind` \i -> unit i)
$ stack
print
$ (pop
`bind` \i -> push 10
`bind_` push 12
`bind_` unit i)
$ stack
print
$ (pop
`bind` \i1 -> pop
`bind` \i2 -> push 10
`bind_` push 12
`bind_` (unit $ i1 + i2))
$ stack
print
$ (push 10
`bind_` empty
`bind_` push 11
`bind_` push 12)
$ stack