Intial import of some haskell programs.
[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 -> [(s, b)]
18 run f (i:input) s =
19   (s', o): (run f input s')
20   where
21     (s', o) = f i s
22 run _ [] _ = []
23
24 simulateIO :: (Read 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 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 (s', o)
41       simulateIO f s'
42
43 printOutput :: (Show s, Show o) => (s, o) -> IO ()
44 printOutput (s, o) = do
45   putStr "Output: "
46   putStr $ show o
47   putStr "\nNew State: "
48   putStr $ show s
49   putStr "\n\n"
50 -- vim: set ts=8 sw=2 sts=2 expandtab: