module GraphRewriting.Graph.Read
(module GraphRewriting.Graph.Read, module GraphRewriting.Graph.Types, module Data.View)
where
import Prelude.Unicode
import GraphRewriting.Graph.Types
import GraphRewriting.Graph.Internal
import Control.Monad.Reader
import qualified Data.IntMap as Map
import qualified Data.IntSet as Set
import Data.View
import Data.List (nub)
type WithGraph n = Reader (Graph n)
readOnly ∷ WithGraph n a → Rewrite n a
readOnly r = liftM (runReader r) ask
readNode ∷ MonadReader (Graph n) m ⇒ Node → m n
readNode (Node n) = readRef n =<< asks nodeMap
inspectNode ∷ (View v n, MonadReader (Graph n) m) ⇒ Node → m v
inspectNode = liftM inspect . readNode
examineNode ∷ (View v n, MonadReader (Graph n) m) ⇒ (v → a) → Node → m a
examineNode f = liftM (examine f) . readNode
readNodeList ∷ MonadReader (Graph n) m ⇒ m [Node]
readNodeList = liftM (map Node . Map.keys) (asks nodeMap)
readEdgeList ∷ MonadReader (Graph n) m ⇒ m [Edge]
readEdgeList = liftM (map Edge . Map.keys) (asks edgeMap)
attachedEdges ∷ (View [Port] n, MonadReader (Graph n) m) ⇒ Node → m [Edge]
attachedEdges = liftM nub . inspectNode
attachedNodes ∷ MonadReader (Graph n) m ⇒ Edge → m [Node]
attachedNodes = liftM (map Node . Set.elems) . readEdge
edgeCardinality ∷ (View [Port] n, MonadReader (Graph n) m) ⇒ Edge → m Int
edgeCardinality e = liftM (length . filter (e ≡) . concat) (mapM inspectNode =<< attachedNodes e)
neighbours ∷ (View [Port] n, MonadReader (Graph n) m) ⇒ Node → m [Node]
neighbours n@(Node i) = do
is ← liftM Set.unions $ mapM readEdge =<< inspectNode n
return $ map Node $ Set.elems $ Set.delete i is
relatives ∷ (View [Port] n, MonadReader (Graph n) m) ⇒ Node → m [Node]
relatives n@(Node i) = do
is ← liftM Set.unions $ mapM readEdge =<< inspectNode n
return $ map Node $ Set.elems is
adverseNodes ∷ MonadReader (Graph n) m ⇒ Node → Port → m [Node]
adverseNodes (Node n) p = liftM (map Node . Set.elems . Set.delete n) (readEdge p)
connected ∷ (View [Port] n, MonadReader (Graph n) m) ⇒ Node → Node → m Bool
connected n1 n2 = liftM (n2 ∈) (relatives n2)
free ∷ (View [Port] n, MonadReader (Graph n) m) ⇒ Port → m Bool
free p = do
c ← edgeCardinality p
return (c ≡ 1)
withNodes ∷ MonadReader (Graph n) m ⇒ (Node → m a) → m [a]
withNodes p = mapM p =<< readNodeList