{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Database.Bolt.Extras.Graph.Internal.AbstractGraph
(
Graph (..)
, vertices
, relations
, emptyGraph
, addNode
, addRelation
, NodeName
, relationName
) where
import Control.Lens (makeLenses, over)
import Data.Map.Strict (Map, insert, notMember)
import Data.Monoid ((<>))
import Data.Text (Text)
import GHC.Generics (Generic)
import Text.Printf (printf)
data Graph n a b = Graph { _vertices :: Map n a
, _relations :: Map (n, n) b
} deriving (Show, Generic)
makeLenses ''Graph
emptyGraph :: Ord n => Graph n a b
emptyGraph = Graph mempty mempty
addNode :: (Show n, Ord n)
=> n
-> a
-> Graph n a b -> Graph n a b
addNode name node graph = if name `notMember` _vertices graph
then over vertices (insert name node) graph
else error . printf "vertex with name %s key already exists" . show $ name
addRelation :: (Show n, Ord n)
=> n
-> n
-> b
-> Graph n a b -> Graph n a b
addRelation startName endName rel graph = if (startName, endName) `notMember` _relations graph
then over relations (insert (startName, endName) rel) graph
else error $ printf "relation with names (%s, %s) already exists" (show startName) (show endName)
type NodeName = Text
relationName :: (NodeName, NodeName) -> Text
relationName (st, en) = st <> "0" <> en