Show input on each simulation step.
[matthijs/master-project/cλash.git] / Sim.hs
1 module Sim (simulate, Circuit, simulateIO) where
2 import Data.Typeable
3
4 simulate f input s = do
5   putStr "Input: "
6   putStr $ show input
7   putStr "\nInitial State: "
8   putStr $ show s
9   putStr "\n\n"
10   foldl1 (>>) (map (printOutput) output)
11   where
12     output = run f input s
13
14 -- A circuit with input of type a, state of type s and output of type b
15 type Circuit a s b = a -> s -> (s, b)
16
17 run :: Circuit a s b -> [a] -> s -> [(a, b, s)]
18 run f (i:input) s =
19   (i, o, s'): (run f input s')
20   where
21     (s', o) = f i s
22 run _ [] _ = []
23
24 simulateIO :: (Read a, Show a, Show b, Show s) => Sim.Circuit a s b -> s -> IO()
25 simulateIO c s = do
26   putStr "Initial State: "
27   putStr $ show s
28   putStr "\n\n"
29   runIO c s
30
31 runIO :: (Read a, Show a, Show b, Show s) => Sim.Circuit a s b -> s -> IO()
32 runIO f s = do
33   putStr "\nInput? "
34   line <- getLine
35   if (line == "") then
36       return ()
37     else
38       let i = (read line) in do
39       let (s', o) = f i s in do
40       printOutput (i, o, s')
41       simulateIO f s'
42
43 printOutput :: (Show i, Show o, Show s) => (i, o, s) -> IO ()
44 printOutput (i, o, s) = do
45   putStr "Input: "
46   putStr $ show i
47   putStr "\nOutput: "
48   putStr $ show o
49   putStr "\nNew State: "
50   putStr $ show s
51   putStr "\n\n"
52 -- vim: set ts=8 sw=2 sts=2 expandtab: