I am trying to work out a data structure for the following situation.
Graph Structure
I plan to have a graph of nodes with un-weighted, directed edges: Graph = [Node]
Each node has:
- Some TBD internal (persistent) state
- A queue of incoming messages
- A type of message it can send determined by a function that accepts the current node state (with the possibility of failure)
- A list of edges
Node { nodeState :: NodeState, inbox :: Queue NodeMessage, nodeMessage :: (NodeState -> Maybe NodeMessage), connections::[NodeEdge] }
Each edge is an intermediary step capturing pending messages for a target node
NodeEdge { pendingMessage:: Maybe NodeMessage, targetNode :: Node }
Message Passing
The message passing happens in phases and is not-conccurent (though the queues may be processed in parallel to reduce computation time).
- Phase 1: Check the inbox of every node, processing any messages and updating the
NodeState
if relevant. - Phase 2: Have every node run
nodeMessage
, if this results inJust NodeMessage
, send NodeMessage to every connection ([NodeEdge]
) - Phase 3: Check every node edge, if it has a message, add it to the target node's message queue.
Monat/ST
My original plan was to assign every node an ID (probably a simple Int) and store each node in a Map Int Node. I haven't tried the ST Monad before but I figured I could use something like ST s (M.Map Int Node)
. For any given phase each node's message send activity could be processed in O(k log N).
On the other hand if nodes/edges were able to update the mutable state of their edges/nodes then any single queue could be processed in O(k).
While the ST/Map method seems fairly intuitive, having the whole graph mutable is beyond me.
Any suggestions / tips / recommended reading?
data NodeEdge f = NodeEdge (Maybe NodeMessage) (f (Node f))
and lettingf==Identity
for immutable graphs andf==STRef s
for mutable graphs. But, if you are concerned with performance, you should simply use a more efficient representation (something like adjacency list/matrix withIntSet
as your "list"). – Cleome