Skip to content

Instantly share code, notes, and snippets.

@jackrusher
Last active February 18, 2025 16:40
Show Gist options
  • Save jackrusher/5018122 to your computer and use it in GitHub Desktop.
Save jackrusher/5018122 to your computer and use it in GitHub Desktop.
A super simple example of inference from a set of triples.
;; knowledge representation, syllogism via knowledge base
(defrecord Triple [subject predicate object])
(def knowledge-base
[(Triple. :Socrates :is-a :Greek)
(Triple. :Greek :is-a :human-being)
(Triple. :human-being :has-property :mortal)])
(defn collect-predicate-along-axis [kb subject predicate axis]
(let [facts (filter #(= subject (:subject %)) kb)
arcs (filter #(= axis (:predicate %)) facts)]
(concat
(filter #(= predicate (:predicate %)) facts)
(mapcat #(collect-predicate-along-axis kb (:object %) predicate axis) arcs))))
(defn get-properties [subject kb]
(map :object (collect-predicate-along-axis kb subject :has-property :is-a)))
(get-properties :Socrates knowledge-base)
;; => (:mortal)
(def knowledge-base
[(Triple. :Berlin :is-a :city)
(Triple. :Berlin :part-of :Germany)
(Triple. :Germany :part-of :EU)
(Triple. :EU :part-of :Eurasia)
(Triple. :Eurasia :part-of :Earth)])
(defn part-of-what? [subject kb]
(map :object (collect-predicate-along-axis kb subject :part-of :part-of)))
(part-of-what? :Berlin knowledge-base)
;; => (:Germany :EU :Eurasia :Earth)
;; Again with more relations
(def knowledge-base
[(Triple. :Berlin :is-a :city)
(Triple. :Berlin :part-of :Germany)
(Triple. :Germany :part-of :Mitteleuropa)
(Triple. :Germany :member-of :EU)
(Triple. :Germany :member-of :NATO)
(Triple. :Mitteleuropa :part-of :Eurasia)
(Triple. :Eurasia :part-of :Earth)])
;; find :part-of and :member-of relations for :Berlin by along the :part-of axis
(reduce #(assoc %1 %2 (map :object (collect-predicate-along-axis knowledge-base :Berlin %2 :part-of)))
{} [:part-of :member-of])
;; => {:member-of (:EU :NATO), :part-of (:Germany :Mitteleuropa :Eurasia :Earth)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment