Logic Programming for Racket
The logic-programming library provides a prolog-like language that can be used within racket programs. Both queries and knowledgebases are s-expressions that can be manipulated programmatically, rather than having a single knowledgebase. The library is intended for racket programs that just need to do a bit of logic, rather than for writing full programs in the provided language. See also the Parenlog package, which puts less focus on programmatic modification of knowledgebases.
1 Example of Use
Take the ‘hello world’ of formal logic:
1. Socrates is a man
2. Men are mortal
3. Therefore, Socrates is mortal
> (define knowledgebase '((man socrates) (:- (mortal X) (man X))))
> (query '(mortal socrates) knowledgebase) (set)
> (query '(mortal plato) knowledgebase) #f
> (query '(mortal X) knowledgebase) (set (ec '(X) 'socrates))
> (query-all '(X socrates) knowledgebase) (list (set (ec '(X) 'man)) (set (ec '(X) 'mortal)))
2 Racket Reference
(require logic-programming) | package: logic-programming |
This section details the bindings provided by the library. The details of the logic language are in the section below.
procedure
(query-gen q kb [trace?]) → generator?
q : (not/c #f) kb : (listof? (not/c #f)) trace? : boolean? = #f
struct
(struct ec (vars val) #:extra-constructor-name make-ec) vars : (listof? variable?) val : any/c
3 Language Reference
The logic language provided by this library is very similar to prolog. Since it’s unlikely someone interested in using it won’t have some prolog experience, it’ll be easiest to describe the differences. For use, see Example of Use.
3.1 syntax
An s-expression syntax is used. Facts and Queries are written '(predicate-name arg1 ... argn), and Rules are written '(:- (predicate-name arg1 ... argn) body), where body is a Fact (using ‘,’ and ‘;’ for ‘and’ and ‘or’ is not possible, a Rule might look like '(:- (p X) (and (q X) (r X)))). Don’t forget to quote literal sections of this code before using it, there’s no binding provided for :- or anything.
3.2 defined predicates
and: '(and p q) is like p,q in prolog
or: '(or p q) is like p;q in prolog
unprovable: equivalent to prolog’s not. WARNING: if you’re not familiar with it, prolog’s not can be fairly unintuitive. Hopefully unprovable better expresses what’s meant by it.
\\=: equivalent to prolog’s \=. The double slash is because racket allows backslash escapes in symbols, so without it it’d be the same as =
=: equivalent to prolog’s =. If it weren’t defined by default, it could be produced by adding '(= X X) to a knowledgebase.