module Data.RDF.TriplesGraph(TriplesGraph, empty, mkRdf, triplesOf, uniqTriplesOf, select, query)
where
import Prelude hiding (pred)
import Control.DeepSeq (NFData)
import Data.Binary
import qualified Data.Map as Map
import Data.RDF.Namespace
import Data.RDF.Query
import Data.RDF.Types
import Data.List (nub)
import GHC.Generics
newtype TriplesGraph = TriplesGraph (Triples, Maybe BaseUrl, PrefixMappings)
deriving (Generic,NFData)
instance Binary TriplesGraph
instance RDF TriplesGraph where
baseUrl = baseUrl'
prefixMappings = prefixMappings'
addPrefixMappings = addPrefixMappings'
empty = empty'
mkRdf = mkRdf'
triplesOf = triplesOf'
uniqTriplesOf = uniqTriplesOf'
select = select'
query = query'
instance Show TriplesGraph where
show gr = concatMap (\t -> show t ++ "\n") (triplesOf gr)
prefixMappings' :: TriplesGraph -> PrefixMappings
prefixMappings' (TriplesGraph (_, _, pms)) = pms
addPrefixMappings' :: TriplesGraph -> PrefixMappings -> Bool -> TriplesGraph
addPrefixMappings' (TriplesGraph (ts, baseURL, pms)) pms' replace =
let merge = if replace then flip mergePrefixMappings else mergePrefixMappings
in TriplesGraph (ts, baseURL, merge pms pms')
baseUrl' :: TriplesGraph -> Maybe BaseUrl
baseUrl' (TriplesGraph (_, baseURL, _)) = baseURL
empty' :: TriplesGraph
empty' = TriplesGraph ([], Nothing, PrefixMappings Map.empty)
mkRdf' :: Triples -> Maybe BaseUrl -> PrefixMappings -> TriplesGraph
mkRdf' ts baseURL pms = TriplesGraph (ts, baseURL, pms)
triplesOf' :: TriplesGraph -> Triples
triplesOf' (TriplesGraph (ts, _, _)) = ts
uniqTriplesOf' :: TriplesGraph -> Triples
uniqTriplesOf' = nub . expandTriples
select' :: TriplesGraph -> NodeSelector -> NodeSelector -> NodeSelector -> Triples
select' g s p o = filter (matchSelect s p o) $ triplesOf g
query' :: TriplesGraph -> Maybe Subject -> Maybe Predicate -> Maybe Object -> Triples
query' g s p o = filter (matchPattern s p o) $ triplesOf g
matchSelect :: NodeSelector -> NodeSelector -> NodeSelector -> Triple -> Bool
matchSelect s p o t =
match s (subjectOf t) && match p (predicateOf t) && match o (objectOf t)
where
match Nothing _ = True
match (Just fn) n = fn n
matchPattern :: Maybe Subject -> Maybe Predicate -> Maybe Object -> Triple -> Bool
matchPattern subj pred obj t = smatch t && pmatch t && omatch t
where
smatch trp = matchNode subj (subjectOf trp)
pmatch trp = matchNode pred (predicateOf trp)
omatch trp = matchNode obj (objectOf trp)
matchNode :: Maybe Node -> Node -> Bool
matchNode Nothing _ = True
matchNode (Just n1) n2 = n1 == n2