FIFO Example Haskell


import Data.List
import Data.Maybe
import Data.Map
--import qualified Data.Map as Map

type Pipe = [Int]
type PipeMap = Map String Pipe

pipes = fromList [ ("A",[]), ("B",[]) ]

-- Abstract agent class

class AgentClass a where
tick :: a -> PipeMap -> PipeMap

data Agent = Producer { tickP :: Pipe -> Pipe, outqP :: String }
| Modifier { tickM :: (Pipe,Pipe) -> (Pipe,Pipe), inqM :: String, outqM :: String }
| Consumer { tickC :: Pipe -> Pipe, inqC :: String }

instance AgentClass Agent where
tick (Producer tick outq) ps =
let
o0 = fromJust (Data.Map.lookup outq ps)
o1 = tick o0
in
Data.Map.update (\_->Just o1) outq ps
tick (Modifier tick inq outq) ps =
let
i0 = fromJust (Data.Map.lookup inq ps)
o0 = fromJust (Data.Map.lookup outq ps)
(i1,o1) = tick (i0,o0)
in
Data.Map.update (\_->Just i1) inq
(Data.Map.update (\_->Just o1) outq ps)
tick (Consumer tick inq) ps =
let
i0 = fromJust (Data.Map.lookup inq ps)
i1 = tick i0
in
Data.Map.update (\_->Just i1) inq ps

-- Producer

producer = Producer produce "A"
produce o = o++[1]

-- Modifier

modifier = Modifier modify "A" "B"
modify (i:is,o) = (is, o++[i+1])
modify ([],o) = ([],o)

-- Consumer

consumer = Consumer consume "B"
consume (i:is) = is
consume [] = []

-- Compose Agents

agents = [producer, modifier, consumer]

next :: [Agent] -> PipeMap -> PipeMap
next as qs = foldr (\a q->tick a q) qs as

main = take 5 (iterate (\qs->next agents qs) pipes)

One thought on “FIFO Example Haskell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s