C#: semantic networks with default reasoning
A semantic network represents knowledge as nodes joined by links such as is-a. Properties attach to nodes, and a node inherits properties from its ancestors. Looking up a property means walking up the is-a chain until some node defines it.
C#
using System;
using System.Collections.Generic;
class Node {
public string Name;
public Node Parent;
public Dictionary<string, bool> Properties = new Dictionary<string, bool>();
public Node(string name, Node parent) {
Name = name;
Parent = parent;
}
public bool? Lookup(string property) {
for (Node n = this; n != null; n = n.Parent) {
if (n.Properties.TryGetValue(property, out bool value)) {
return value;
}
}
return null;
}
}
class Program {
static void Main() {
var animal = new Node("animal", null);
animal.Properties["alive"] = true;
var bird = new Node("bird", animal);
bird.Properties["flies"] = true;
bird.Properties["feathers"] = true;
var penguin = new Node("penguin", bird);
penguin.Properties["flies"] = false;
var tweety = new Node("tweety", bird);
var opus = new Node("opus", penguin);
foreach (var (node, property) in new[] { (tweety, "flies"), (opus, "flies"), (opus, "feathers"), (opus, "swims") }) {
Console.WriteLine(node.Name + " " + property + ": " + (node.Lookup(property)?.ToString() ?? "unknown"));
}
}
}