Skip to content

Instantly share code, notes, and snippets.

@jathak
Last active August 7, 2018 23:10
Show Gist options
  • Save jathak/84c01c29d8c999fa3e8fe807159d5d1d to your computer and use it in GitHub Desktop.
Save jathak/84c01c29d8c999fa3e8fe807159d5d1d to your computer and use it in GitHub Desktop.
; Adapted from John DeNero's NLP lecture from Python to Logic
; Run at logic.cs61a.org
; Helpers
(fact (append () ?lst ?lst))
(fact (append (?f . ?r) ?x (?f . ?s))
(append ?r ?x ?s))
; Types of Leaves
(fact (leaf N))
(fact (leaf V))
(fact (leaf J))
; Types of Non-Leaves
(fact (phrase NP))
(fact (phrase VP))
(fact (phrase S))
; Lexicon
(fact (N cows))
(fact (N buffalo))
(fact (N dogs))
(fact (V intimidate))
(fact (V buffalo))
(fact (J northern))
(fact (J buffalo))
; Grammar
(fact (S (NP . ?np) (VP . ?vp))
(NP . ?np)
(VP . ?vp))
(fact (NP (N ?n))
(N ?n))
(fact (NP (J ?j) (N ?n))
(J ?j)
(N ?n))
(fact (VP (V ?v) (NP . ?np))
(V ?v)
(NP . ?np))
; Parse leaves
(fact (parse-piece (?word) (?type ?word))
(leaf ?type)
(?type ?word))
; Parse one-item phrases
(fact (parse-piece ?words (?type ?clause))
(phrase ?type)
(?type ?clause)
(parse-piece ?words ?clause))
; Parse two-item phrases
(fact (parse-piece ?words (?type ?clause1 ?clause2))
(phrase ?type)
(?type ?clause1 ?clause2)
(parse-piece ?words1 ?clause1)
(parse-piece ?words2 ?clause2)
(append ?words1 ?words2 ?words))
; Parse sentences
(fact (parse ?words (S . ?clauses))
(parse-piece ?words (S . ?clauses)))
; Example: Finds all* sentences and their structures
; * not quite all, since the Logic interpreter has a depth limit to its search
; (query (parse ?sentence ?structure))
; Example: Finds all structures for "buffalo buffalo buffalo buffalo"
; (query (parse (buffalo buffalo buffalo buffalo) ?structure))
(fact (all-buffalo buffalo))
(fact (all-buffalo buffalo . ?rest)
(all-buffalo . ?rest))
; Example: Finds all sentences/structures that are just the word buffalo repeated
; (query (parse ?sentence ?structure)
; (all-buffalo . ?sentence))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment