-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTreeWalkST.hs
52 lines (45 loc) · 1.22 KB
/
TreeWalkST.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
import Data.Maybe
import Control.Applicative
import Control.Monad
import Control.Monad.Fix
import Control.Monad.ST
import Stack
import Queue
data Data = Data { ide :: Int, items :: [Data] }
main = let
tree = [
Data 1 [
Data 11 [
Data 111 []
],
Data 12 [
Data 121 [],
Data 122 []
]
],
Data 2 [
Data 21 [
Data 211 [],
Data 212 []
],
Data 22 []
]]
action = print . ide
in mapM_ (\(m, f) -> print m >> f action tree) [
("Calling Depth-first Pre-order Recursive variant", dfpor),
("Calling Depth-First reversed-Pre-Order on-Stack variant", dfpos),
("Calling Breadth-first on-Queue variant", bfq)]
statefulWalk funcs action tree = do
(insert, extract) <- funcs
mapM_ insert tree
whileJust extract $ \x -> do
action x
mapM_ insert $ items x
mkFuncs ctor i o = stToIO $ ctor >>= \s -> return (stToIO . i s, stToIO $ o s)
dfpor action = mapM_ $ \x -> do
action x
dfpor action (items x)
dfpos = statefulWalk $ mkFuncs newStack push pop
bfq = statefulWalk $ mkFuncs newQueue enqueue dequeue
-- auxiliaries
whileJust cond body = fix (\w -> cond >>= maybe (return ()) (body >=> const w))