aboutsummaryrefslogtreecommitdiff
path: root/lib/core/graph.ml
blob: b097af1b4596c1db46e1cd3d88f3a702968d230f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
(* This is a simple functional RDF graph structure.

   It uses CCMultiMap with keys of type Triple.Subject.t and values of type
   (Triple.Predicate.t * Triple.Object.t).

   This allows efficient quering in the order subject -> predicate -> object.But
   not in any other.

   This can be improved.
*)

module OrderedSubject = struct
  type t = Triple.Subject.t

  let compare a b =
    Term.compare
      (Triple.Subject.to_term a)
      (Triple.Subject.to_term b)
end

module OrderedPredicateObject = struct
  type t = Triple.Predicate.t * Triple.Object.t

  let compare (a_p,a_o) (b_p,b_o) =
    let p_compared = Term.compare
        (Triple.Predicate.to_term a_p)
        (Triple.Predicate.to_term b_p) in
    if p_compared = 0 then
      Term.compare
        (Triple.Predicate.to_term a_o)
        (Triple.Predicate.to_term b_o)
    else
      p_compared
end

module GraphMap = CCMultiMap.Make(OrderedSubject)(OrderedPredicateObject)

type t = GraphMap.t

let empty = GraphMap.empty

let add graph (triple:Triple.t) =
  GraphMap.add graph triple.subject (triple.predicate, triple.object')

let add_seq graph triples =
  Seq.fold_left add graph triples

let remove_triple graph (triple:Triple.t) =
  GraphMap.remove graph triple.subject (triple.predicate, triple.object')

let union = GraphMap.union

let difference = GraphMap.diff

let intersection = GraphMap.inter

let member_subject =
  GraphMap.mem

let to_list graph =
  GraphMap.fold graph []
    (fun triples subject (predicate, object') ->
       Triple.make subject predicate object' :: triples)