1 --!!! Testing IOExts.fixIO
3 > module FixIOTest where
6 > import IOExts( fixIO )
8 First a recursively-defined environment in the normal way:
10 > env = foldl (\env' (s,v) -> enter env' s v)
12 > [ ("f", (1, fst (fromJust (look env "g")))) ,
13 > ("g", (2, fst (fromJust (look env "f")))) ]
15 > env2 = let vF = (1, fst (fromJust (look env2 "g")))
16 > vG = (2, fst (fromJust (look env2 "f")))
17 > in enter (enter empty "f" vF) "g" vG
19 Which yields these correct evaluations:
20 look env' "f" ==> (1,2)
21 look env' "g" ==> (2,1)
23 Now let's add some IO to each "store action" and use foldM/fixIO to
27 > do env <- fixIO (\env -> do
28 > foldM (\env' (s,vM) -> do v <- vM
29 > return (enter env' s v))
31 > [ ("f", do putStrLn "storing f"
32 > return (1, fst (fromJust (look env "g")))) ,
33 > ("g", do putStrLn "storing g"
34 > return (2, fst (fromJust (look env "f")))) ] )
35 > print (look env "f")
36 > print (look env "g")
40 > do env <- fixIO (\env -> do
41 > let vF = (1,fst (fromJust (look env "g")))
42 > vG = (2,fst (fromJust (look env "f")))
43 > putStrLn "storing f and g"
44 > return $ enter (enter empty "f" vF) "g" vG
46 > putStrLn "Constructed environment"
48 > print (look env "f")
49 > print (look env "g")
52 But this unfortunately dies a horrible death:
58 Program error: {_Gc Black Hole}
60 If I comment out the "print" statements I get:
66 and it terminates properly.
68 ----------------------------------------------------------------
70 ----------------------------------------------------------------
73 > enter :: Table a -> String -> a -> Table a
74 > look :: Table a -> String -> Maybe a
76 ----------------------------------------------------------------
77 -- A very simple environment implemented as functions:
78 ----------------------------------------------------------------
81 > type Table a = String -> Maybe a
83 > enter t s1 x s2 | s1==s2 = Just x
84 > | otherwise = look t s2
88 ----------------------------------------------------------------
89 -- A very simple environment implemented using association lists:
90 ----------------------------------------------------------------
92 > type Table a = [(String,a)]
94 > enter t s x = (s,x):t
95 > look t s = lookup s t