Friday, March 12, 2010

Data-Driven Semantic Network

Here's a super-simple version of a basic semantic network using only strings. There's not much it couldn't be extended to do. However, using only strings in this way is likely to be sub-optimal. For example, when we follow a link from one node to another, in order to go any further we have to do a second lookup, etc.

But I have to say I'm not as displeased with the look and feel of the string version as I had thought I would be, so I think this is the version I'll extend.

Standard disclaimers: as-is, no warranty or implied fitness, use at your own risk.
open System.Collections.Generic 

type Rel () =

let store =
new Dictionary<string,Dictionary<string,HashSet<string>>>()

member private this.TryAdd
((n0,l,n1):string*string*string) =
let d =
match store.TryGetValue n0 with
| (true,d0) -> d0
| (false,_) ->
let d0 = new Dictionary<string,HashSet<string>>()
let h =
match d.TryGetValue l with
| (true,h0) -> h0
| (false,_) ->
let h0 = new HashSet<string>()
h.Add n1 |> ignore

static member (+=)
((r:Rel),((nln):string*string*string)) =
r.TryAdd nln

let r = Rel()

r += ("mammal","isA","animal") |> ignore
r += ("dog","isA","mammal") |> ignore
r += ("spot","isA","dog") += ("spot","isA","pet") |> ignore

No comments: