Chapter 1: Introduction to Symbolic Reasoning
Symbolic reasoning forms the bedrock of classical artificial intelligence. Before statistical and neural network based methods dominated the landscape, AI researchers built systems that manipulated explicit symbols according to formal rules. This chapter introduces the fundamental concepts that underpin symbolic AI and explains why these ideas remain essential for building systems capable of genuine reasoning.
All code examples for this chapter are in source-code/01-introduction-to-symbolic-reasoning/. Each example is a self-contained Racket module that you can run directly to see the concepts in action. Later chapters share small helpers (string, math, logic, and expression evaluation) factored into source-code/utils/; the final section of this chapter, Shared Utilities, gives that module map once you have seen the examples that use it.
Propositional and Predicate Logic
At the heart of symbolic reasoning lies formal logic. Propositional logic deals with simple true/false statements and logical connectives like AND, OR, NOT, and IMPLIES. Predicate logic extends this with variables, quantifiers, and relations, enabling us to express complex statements about objects and their properties.
The example file 01-propositional-logic.rkt builds a propositional evaluator without copying logic helpers from other files:
1 #lang racket
2 (require racket/dict racket/match)
3
4 (provide logical-and logical-or logical-not logical-implies logical-iff
5 evaluate make-environment truth-table truth-table-display)
6
7 (define (logical-and a b) (if (and a b) #t #f))
8 (define (logical-or a b) (if (or a b) #t #f))
9 (define (logical-not a) (if a #f #t))
10 (define (logical-implies a b) (if a b #t))
11
12 (define (truth-table vars expr)
13 (for/list ([i (in-range (expt 2 (length vars)))])
14 (define assignment
15 (for/list ([v vars] [k (in-naturals)])
16 (if (bitwise-bit-set? i k) #t #f)))
17 (list assignment (evaluate expr (make-environment vars assignment)))))
18
19 (define (evaluate expr env)
20 (match expr
21 [(== #t) #t]
22 [(== #f) #f]
23 [(? symbol? s) (dict-ref env s #f)]
24 [`(not ,a) (logical-not (evaluate a env))]
25 [`(and ,a ,b) (logical-and (evaluate a env) (evaluate b env))]
26 [`(or ,a ,b) (logical-or (evaluate a env) (evaluate b env))]
27 [_ (raise-argument-error 'evaluate "propositional expr" expr)]))
Key concepts demonstrated:
- Propositional operators: AND, OR, NOT, IMPLIES, IFF with strict boolean returns
- Evaluation: Computing truth values for formulas given variable assignments
- Truth tables: Pure function returning a list of rows, with
truth-table-displayfor printing
The latest version of this code uses Racket truth uniformly: anything except #f counts as true, and each connective returns #t or #f only.
Output looks like:
1 $ racket 01-propositional-logic.rkt
2 === Propositional Logic Examples ===
3 P AND Q with x=#t, y=#f:
4 #f
5
6 P OR Q with x=#t, y=#f:
7 #t
8
9 P IMPLIES Q with x=#t, y=#f:
10 #f
11
12 P IFF Q with x=#t, y=#f:
13 #f
14
15 NOT P with x=#t:
16 #f
17
18 (x OR y) AND (x IMPLIES y) with x=#t, y=#f:
19 #f
20
21 Truth table for (x OR y) AND (x IMPLIES y):
22 (#f #f) => #f
23 (#t #f) => #f
24 (#f #t) => #t
25 (#t #t) => #t
26
27 Note: table is #f for (#f #f) and (#t #f), #t for (#f #t) and (#t #t).
Automated Theorem Proving and Logic Programming
Once we have formal representations, we need methods to derive new knowledge from existing knowledge. Automated theorem proving encompasses algorithms that can prove logical statements automatically. Logic programming turns logical inference into a computational paradigm where programs are sets of logical clauses.
Unification
The unification algorithm (02-unification.rkt) finds substitutions that make two terms identical:
1 (define (subst-lookup var env)
2 (let loop ([v var])
3 (define p (assq v env))
4 (if p (loop (cdr p)) v)))
5
6 (define (unify x y env)
7 (let ([x-val (subst x env)] [y-val (subst y env)])
8 (cond
9 [(equal? x-val y-val) env]
10 [(var? x-val) (if (occurs? x-val y-val env) (error 'unify "occurs check") (cons (cons x-val y-val) env))]
11 [(and (pair? x-val) (pair? y-val))
12 (let ([env1 (unify (car x-val) (car y-val) env)])
13 (unify (cdr x-val) (cdr y-val) env1))]
14 [else (error 'unify "clash ~a vs ~a" x-val y-val)])))
Key concepts:
- Chained substitution:
subst-lookupnow chases?x -> ?y -> aso bindings compose - Occurs check: Preventing infinite structures such as
?x = (f ?x) - Proper cdr handling: Dotted pairs unify both
carandcdr, not just thecarpath - Parameterized error model:
unifyraisesexn:fail; callers that want#fwrap it withwith-handlers
Program output looks like:
1 $ racket 02-unification.rkt
2 === Unification Examples ===
3 Unify (?x) with (a):
4 {?x = a}
5
6 Unify (?x ?y) with (a b):
7 {?y = b, ?x = a}
8
9 Unify (?x ?y ?x) with (a b a):
10 {?y = b, ?x = a}
11 Resolved ?x:
12 a
13 Resolved ?y:
14 b
15
16 Unify (f ?x) with (f (g a)):
17 {?x = (g a)}
18 Resolved ?x:
19 (g a)
20
21 Unify (?x loves ?y) with (mary loves john):
22 {?y = john, ?x = mary}
23 Resolved ?x:
24 mary
25 Resolved ?y:
26 john
27
28 Unify (?x ?x) with (a b) - expecting failure:
29 unify: clash: a vs b
30
31 Unify (?x . ?y) with (a . b):
32 {?y = b, ?x = a}
33
34 Chain ?x->?y, ?y->a:
35 resolve ?x = a (should be a)
Forward Chaining
The forward chaining engine in 03-forward-chaining.rkt derives new facts from rules without global mutation at require time:
1 (define current-facts (make-parameter '()))
2 (define (add-fact! fact) (current-facts (cons fact (current-facts))))
3 (define (clear-kb!) (current-facts '()))
4
5 (define (forward-chain rules facts max-iterations #:trace? [trace? #f])
6 (let loop ([all-facts facts] [iter 0])
7 (if (>= iter max-iterations) all-facts
8 (let ([all-new (append-map (lambda (r) (derive-once r all-facts)) rules)])
9 (if (null? all-new) all-facts
10 (loop (append all-new all-facts) (+ iter 1)))))))
current-facts is a parameter, not a plain set! global, so tests can isolate knowledge bases and (require "03-forward-chaining.rkt") no longer prints at load time. Demos live inside (module+ main ...). derive-once uses append-map instead of mutating set! and append, and the trace is opt-in via #:trace?.
Here is sample output:
1 $ racket 03-forward-chaining.rkt
2 === Forward Chaining Example ===
3 Initial facts:
4 (parent tom mary)
5 (parent ann sue)
6 (parent bob ann)
7 (parent tom bob)
8
9 Iteration 0: Derived 2 new facts: ((grandparent bob sue) (grandparent tom ann))
10
11 Grandparent facts:
12 (grandparent bob sue)
13 (grandparent tom ann)
14
15 === Transitive Closure Example ===
16 Initial facts:
17 (edge d e)
18 (edge c d)
19 (edge b c)
20 (edge a b)
21
22 Iteration 0: Derived 4 new facts: ((connected d e) (connected c d) (connected b c) (connected a b))
23 Iteration 1: Derived 3 new facts: ((connected c e) (connected b d) (connected a c))
24 Iteration 2: Derived 2 new facts: ((connected b e) (connected a d))
25 Iteration 3: Derived 1 new facts: ((connected a e))
26
27 All connected pairs:
28 (connected a e)
29 (connected b e)
30 (connected a d)
31 (connected c e)
32 (connected b d)
33 (connected a c)
34 (connected d e)
35 (connected c d)
36 (connected b c)
37 (connected a b)
Knowledge Representation and Reasoning
Raw logic alone is insufficient for real-world applications. We need structured ways to represent knowledge about complex domains. The semantic network example (04-semantic-network.rkt) shows how to build graph-based knowledge representations:
1 (struct triple (subj pred obj) #:transparent)
2 (define current-network (make-parameter '()))
3
4 (define (find-triples #:subj [subj #f] #:pred [pred #f] #:obj [obj #f])
5 (for/list ([t (current-network)]
6 #:when (and (or (not subj) (eq? (triple-subj t) subj))
7 (or (not pred) (eq? (triple-pred t) pred))
8 (or (not obj) (eq? (triple-obj t) obj))))
9 t))
10
11 (define (inherits? obj pred val)
12 (for/or ([ancestor (set->list (isa-closure-set obj))])
13 (member val (find-all ancestor pred))))
Key concepts:
- Triple store: Knowledge as
triplestructs, not plain lists - Wildcard queries:
find-triplesaccepts#fas wildcard;querybuilds on it - Inheritance:
inherits?checks the isa closure instead of manualdescribeinspection - Correct closure:
isa-closure-setuses a visited set, so diamonds and cycles do not duplicate or loop
Search, Planning, and Constraint Satisfaction
Many AI problems can be framed as search through a space of possible states or solutions. The examples demonstrate:
Search Algorithms (05-search-algorithms.rkt)
BFS and DFS are one search parameterized by a combiner. The full loop from 05-search-algorithms.rkt:
1 (define (search start goal combiner #:trace? [trace? #f])
2 (cond
3 [(equal? start goal) (list start)]
4 [else
5 (define visited (make-hash))
6 (define (mark-visited! n) (hash-set! visited n #t))
7 (define (visited? n) (hash-has-key? visited n))
8 (mark-visited! start)
9 (let loop ([frontier (list (list start))])
10 (cond
11 [(null? frontier) #f]
12 [else
13 (define path (car frontier))
14 (define node (car path))
15 (define rest (cdr frontier))
16 (if (equal? node goal)
17 (reverse path)
18 (let* ([nbs (filter-not visited? (get-neighbors node))]
19 [new-paths (map (lambda (n) (cons n path)) nbs)])
20 (for-each mark-visited! nbs)
21 (loop (combiner new-paths rest))))]))]))
22
23 (define (bfs start goal #:trace? [trace? #f])
24 (search start goal (lambda (new rest) (append rest new)) #:trace? trace?))
25
26 (define (dfs start goal #:trace? [trace? #f])
27 (search start goal (lambda (new rest) (append new rest)) #:trace? trace?))
Paths grow by consing onto the front, so the found path is reversed on return and traces read forward. The graph is directed, search handles start == goal without looping, and printing is opt-in via #:trace?. The combiner is the whole difference: BFS appends new paths after the old frontier (a queue), DFS puts them in front (a stack).
Constraint Satisfaction (06-constraint-satisfaction.rkt)
The CSP solver now uses immutable hashes and for/or:
1 (define (satisfies? assignment [cs constraints])
2 (for/and ([c cs])
3 (match-define (list a b) c)
4 (define ca (hash-ref assignment a #f))
5 (define cb (hash-ref assignment b #f))
6 (or (not ca) (not cb) (not (equal? ca cb)))))
7
8 (define (solve-map-coloring [regs regions] [cols colors] [cs constraints])
9 (define (backtrack assigned remaining)
10 (if (null? remaining) assigned
11 (for/or ([color cols])
12 (define assigned* (hash-set assigned (car remaining) color))
13 (and (satisfies? assigned* cs) (backtrack assigned* (cdr remaining))))))
14 (backtrack (hash) regs))
satisfies? takes its constraint list as a parameter, so the same checker works for N-Queens or other CSPs. backtrack threads immutable hashes, which removes the stale binding bug from the mutable version. show-solution handles #f.
Shared Utilities
You may have noticed that several examples above and in later chapters need the same small functions: a string reverse, a dot product, a product t-norm, an arithmetic s-expression evaluator. Earlier drafts copied these into each file, and the copies drifted — different argument checks, different comments, one outright arity bug. The book now factors them into source-code/utils/, one definition each, imported everywhere else:
1 source-code/
2 utils.rkt ; convenience re-export (see below)
3 utils/
4 string.rkt ; string-reverse, string-trim*
5 math.rkt ; dot, sigmoid, hamming, clamp01
6 logic.rkt ; t-and, t-and-list, t-not, t-impl
7 eval.rkt ; eval-arith, ast-size helpers
Highlights from the four modules, rather than their full source (the files themselves are short and worth reading):
string-reverseraises a contract error on non-strings. Four chapters import it instead of defining their own.dotchecks equal lengths before multiplying — the most common mistake when adding a new embedding dimension in Chapter 6.t-and-listreturns1.0for the empty case, matching the logical identity for universal quantification over an empty domain in the LTN example.eval-arithbinds variables through a hash table, ending the hash-vs-alist drift between copies;ast-sizecounts AST nodes for the parsimony scores of Chapters 8 and 9.
Not every evaluator collapses to one function. Files needing division, sq, pow2, pow3, or ite extend eval-arith locally: utils holds the common core, chapter files hold the grammar-specific extension.
If a file needs helpers from several utils at once, the aggregator re-exports all four:
1 (require "../utils.rkt") ; one-line form, re-exports everything
2 (require "../utils/math.rkt") ; or single concern
Try it in a REPL from any chapter directory:
1 (require "../utils/string.rkt" "../utils/math.rkt" "../utils/logic.rkt")
2
3 (string-reverse "live") ; => "evil"
4 (dot '(0.9 0.1) '(0.6 0.6)) ; => 0.6
5 (t-impl 0.9 0.2) ; => 0.28 ; weak: strong premise, weak conclusion
Each utils file raises exn:fail:contract with a named argument on misuse, so mistakes point to the caller rather than to a deep stack trace.
Symbolic reasoning complements modern machine learning by providing explicit, interpretable representations of knowledge and inference. The examples in this chapter demonstrate the core techniques that form the foundation for program synthesis and neurosymbolic AI systems explored in later chapters.
Running the Examples
All examples are self-contained Racket modules. The shared helpers require no external packages.
1 cd source-code/01-introduction-to-symbolic-reasoning
2 racket 01-propositional-logic.rkt # Propositional logic evaluator
3 racket 02-unification.rkt # Unification algorithm
4 racket 03-forward-chaining.rkt # Forward chaining inference
5 racket 04-semantic-network.rkt # Semantic networks
6 racket 05-search-algorithms.rkt # Search algorithms (BFS/DFS)
7 racket 06-constraint-satisfaction.rkt # CSP solver
8
9 # run as libraries without side effects
10 racket -e '(require "01-propositional-logic.rkt") (displayln (evaluate (quote (and x y)) (quote ((x . #t) (y . #f)))))'
11
12 # run tests for this chapter
13 raco test .
Each file has (module+ main ...) for demos and (module+ test ...) for rackunit checks. Running raco test in any source-code/ subdirectory executes the tests without printing demos.