Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 22nd, 2012  |  syntax: None  |  size: 2.10 KB  |  hits: 5  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import Control.Monad.ST
  2. import Data.STRef
  3.  
  4. -- Primitive actions
  5.  
  6. getSignal wire = wire GetSignal
  7.  
  8. setSignal wire x = wire (SetSignal x)
  9.  
  10. addAction wire proc = wire (AddAction proc)
  11.  
  12. -- Wire implementation
  13.  
  14. data WireAction b a = GetSignal | SetSignal a | AddAction b
  15.  
  16. data WireReturn a = Done | Signal a deriving (Show)
  17.  
  18. makeWire = do
  19.     signalValue <- newSTRef 0
  20.     actionProcedures <- newSTRef []
  21.     return $ \arg -> case arg of
  22.         GetSignal -> do
  23.             signal <- readSTRef signalValue
  24.             return (Signal signal)
  25.         (SetSignal newSignal) -> do
  26.             signal <- readSTRef signalValue
  27.             if newSignal /= signal
  28.                 then do
  29.                     writeSTRef signalValue newSignal
  30.                     procs <- readSTRef actionProcedures
  31.                     callEach procs
  32.                 else return ()
  33.             return Done
  34.         (AddAction proc) -> do
  35.             modifySTRef actionProcedures (proc:)
  36.             return Done
  37.  
  38. callEach [] = return ()
  39. callEach (p:procs) = do
  40.     p
  41.     callEach (procs)
  42.  
  43. testMakeWire = runST $ do
  44.     a <- makeWire
  45.     x <- getSignal a
  46.     setSignal a 1
  47.     y <- getSignal a
  48.     return [x,y]
  49.  
  50.  
  51.  
  52. -- Compound actions
  53.  
  54. --inverter input output = addAction input invertInput where
  55. --    invertInput = setSignal output newValue where
  56. --        newValue = logicalNot (getSignal input)
  57.  
  58. --andGate a1 a2 output = do
  59. --    addAction a1 andActionProc
  60. --    addAction a2 andActionProc
  61. --    where
  62. --        andActionProc = setSignal output newValue where
  63. --            newValue = (&&) (getSignal a1) (getSignal a2)
  64.  
  65. --orGate o1 o2 output = do
  66. --    addAction o1 orActionProc
  67. --    addAction o2 orActionProc
  68. --    where
  69. --        orActionProc = setSignal output newValue where
  70. --            newValue = (||) (getSignal o1) (getSignal o2)
  71.  
  72. -- Logical functions
  73.  
  74. logicalNot 0 = 1
  75. logicalNot 1 = 0
  76. logicalNot _ = error "Invalid signal (NOT)"
  77.  
  78. logicalAnd 0 0 = 0
  79. logicalAnd 0 1 = 0
  80. logicalAnd 1 0 = 0
  81. logicalAnd 1 1 = 1
  82. logicalAnd _ _ = error "Invalid signal (AND)"
  83.  
  84. logicalOr 0 0 = 0
  85. logicalOr 0 1 = 1
  86. logicalOr 1 0 = 1
  87. logicalOr 1 1 = 1
  88. logicalOr _ _ = error "Invalid signal (OR)"