Chapter 6
Semi-Certified Interactive Logic Programming
This chapter studies an embedded Domain Specific Language for logic programming. First, we give a quick introduction of Kanren, a purely functional implementation of this language and, second, we extend the HOL Light theorem prover in order to introduce the relational paradigm in its tactics mechanism.
6.1Kanren and relational programming#
The central tenet of relational programming is that programs corresponds to relations that generalize mathematical functions; our interest here is to deepen our understanding of the underlying concepts and data structures of languages in the miniKanren family. The main reference that drives our work is D. Friedman, W. E. Byrd, and O. Kiselyov. The Reasoned Schemer, Second Edition. MIT Press, 2018 and advanced topics are discussed in Byrd’s dissertation W. E. Byrd. Relational Programming in miniKanren: Techniques, Applications, and Implementations. Indiana University, Bloomington, IN, 2009. PhD dissertation.
The heavy use of higher order functions, infinite streams of objects and unification à-la Robinson makes possible to implement Kanren J. Hemann and D. P. Friedman. Kanren: a Minimal Functional Core for Relational Programming. 2013. Scheme2013, Alexandria, a purely functional core of miniKanren; we repeat the exercise of coding it using different programming languages, in particular
Python. We provide both a complete implementation of the abstract definition and a
test suite that stresses our functions against all questions in the
reference book. Moreover, we characterize our code with a fair
enumeration strategy based on the dovetail techniques used in the
enumeration of the Rationals numbers; precisely, the monadic function
mplus(streams, interleaving) enumerates the states space
streams, using different strategies according to the argument
interleaving.
In order to understand states enumeration can be helpful to use a “matrix
notation”, that associates a row to each stream α of states in
streams, which is an iterable object over a countably,
possibly infinite, set of states streams, so the matrix could have
infinite rows. In parallel, since each states stream α lying on a row is an
iterable object over a countably, possibly infinite, set of
satisfying states, the matrix could have infinite columns too;
therefore, the matrix we are building could be infinite in both dimensions.
So, let streams be represented as
where each is a state that carries a substitution which satisfies
the relation under study. Such states are visited according to the
dovetail techniques which enumerates by interleaving state
objects lying on the same rising diagonal, resulting in a
fair, complete scheduler in the sense that every satisfying
state object will be reached, eventually. For the sake of clarity,
enumeration proceeds as follows
with respect to its implementation
def mplus(streams, interleaving):
if interleaving:
try: α = next(streams)
except StopIteration: return
else: S = [α]
while S:
for j in reversed(range(len(S))):
β = S[j]
try: s = next(β)
except StopIteration: del S[j]
else: yield s
try: α = next(streams)
except StopIteration: pass
else: S.append(α)
else:
for α in streams: yield from αScheme. We provide our implementation using the same language that original authors use for their canonical version. We diverge from them in the way we represent substitutions, choosing an union-find data structure that allows us to maintain a balanced tree to track associations. The overhead work that was necessary to implement a fully-flagged Kanren yield a Scheme library to define and manipulate infinite streams of objects, and this allows us to have another way to define Riordan arrays for free, such as
(test '((1)
(1 1)
(1 2 1)
(1 3 3 1)
(1 4 6 4 1)
(1 5 10 10 5 1)
(1 6 15 20 15 6 1)
(1 7 21 35 35 21 7 1)
(1 8 28 56 70 56 28 8 1)
(1 9 36 84 126 126 84 36 9 1))
((list○take 10) (riordan-array stream:1s stream:1s)))lying on the procedural abstraction riordan-array that consumes two
formal power series and produces a stream of lists, each one denoting a
triangle’s row; its definition is clear and elegant in our opinion,
(define riordan-array
(Λ (d h)
(stream:dest/car+cdr (d ∅)
((dcar dcdr) (stream:cons
(list dcar)
((stream:zip-with cons)
dcdr (riordan-array (series:× d h) h)))))))where stream:× denotes the series convolution operator and
the syntactic abstraction Λ is defined as an “augmented lambda” form
that allows us to define delayed by means of delay-force,
(define-syntax Λ
(syntax-rules ()
((Λ args body ...)
(lambda args (delay-force (begin body ...))))))Smalltalk. This implementation is an exercise in object-oriented programming and its coding has been driven by a test-first approach K. Beck. Test-Driven Development: By Example. Pearson Education, 2002 and it is a literal port of the canonical one.
OCaml. Finally, this version is preparatory for the extension of the HOL Light theorem prover which we are going to describe in the rest of this chapter.
All these prototypes can be found in M. Nocentini. Kanren Implementations, 2018. In the following repositories, indexed by programming languages: description [Python] https://github.com/massimo-nocentini/microkanrenpy [Scheme] https://github.com/massimo-nocentini/on-scheme/blob/master/src/microkanren.scm [Smalltalk] https://github.com/massimo-nocentini/microkanrenst [OCaml] https://github.com/massimo-nocentini/kanren-light description respectively and some examples follows using the Scheme implementation to show the power of the present paradigm.
Example 6.1. The context free grammar that defines the set of Dyck paths
is encoded in the relation dyckº defined by the Kanren goal
(define dyckº
(lambda (α)
(condº/§
((nullº α))
((fresh (β γ) (∧
(dyckº β)
(dyckº γ)
(appendº `(○ . ,β) `(● . ,γ) α)))))))and an enumeration is reported in the margin.
(()
(○ ●)
(○ ○ ● ●)
(○ ● ○ ●)
(○ ○ ○ ● ● ●)
(○ ● ○ ○ ● ●)
(○ ○ ● ● ○ ●)
(○ ● ○ ● ○ ●)
(○ ○ ● ○ ● ●)
(○ ● ○ ○ ○ ● ● ●)
(○ ○ ● ● ○ ○ ● ●)
(○ ● ○ ● ○ ○ ● ●)
(○ ○ ○ ● ● ● ○ ●)
(○ ● ○ ○ ● ● ○ ●)
(○ ○ ● ● ○ ● ○ ●)
(○ ● ○ ● ○ ● ○ ●)
(○ ○ ○ ○ ● ● ● ●)
(○ ● ○ ○ ● ○ ● ●)
(○ ○ ● ● ○ ○ ○ ● ● ●)
(○ ● ○ ● ○ ○ ○ ● ● ●)
(○ ○ ○ ● ● ● ○ ○ ● ●)
(○ ● ○ ○ ● ● ○ ○ ● ●)
(○ ○ ● ● ○ ● ○ ○ ● ●)
(○ ● ○ ● ○ ● ○ ○ ● ●)
(○ ○ ● ○ ● ● ○ ●)
(○ ● ○ ○ ○ ● ● ● ○ ●)
(○ ○ ● ● ○ ○ ● ● ○ ●)
(○ ● ○ ● ○ ○ ● ● ○ ●)
(○ ○ ○ ● ● ● ○ ● ○ ●)
(○ ● ○ ○ ● ● ○ ● ○ ●)
(○ ○ ● ● ○ ● ○ ● ○ ●)
(○ ● ○ ● ○ ● ○ ● ○ ●)
(○ ○ ● ○ ○ ● ● ●)
(○ ● ○ ○ ○ ○ ● ● ● ●)
(○ ○ ● ● ○ ○ ● ○ ● ●)
(○ ● ○ ● ○ ○ ● ○ ● ●)
(○ ○ ○ ● ● ● ○ ○ ○ ● ● ●)
(○ ● ○ ○ ● ● ○ ○ ○ ● ● ●)
(○ ○ ● ● ○ ● ○ ○ ○ ● ● ●)
(○ ● ○ ● ○ ● ○ ○ ○ ● ● ●)
(○ ○ ● ○ ● ● ○ ○ ● ●)
(○ ● ○ ○ ○ ● ● ● ○ ○ ● ●))First Dyck paths enumerated by relation dyckº.
Example 6.2. The recurrence relation for the Fibonacci numbers
is encoded in the relation fibonacciº defined by the goal
(define fibonacciº
(lambda (depth n α)
(cond
((zero? depth) (≡ α (list n)))
(else (fresh (β γ)
(∧
(fibonacciº (sub1 depth) (sub1 n) β)
(fibonacciº (sub1 depth) (sub2 n) γ)
(appendº β γ α)))))))which enumerates the following identities
compacted in where .
Example 6.3. The recurrence relation for the Pascal triangle
is encoded in the relation tartagliaº defined by the goal
(define tartagliaº
(lambda (depth n k α)
(cond
((zero? depth) (≡ α (list (list n k))))
(else (fresh (β γ)
(∧
(tartagliaº (sub1 depth) (sub1 n) (sub1 k) β)
(tartagliaº (sub1 depth) (sub1 n) k γ)
(appendº β γ α)))))))which enumerates the following identities
compacted in for – recall that .
6.2Toward certified computation#
Theorem provers are employed to construct logically verified truths. In this work, we propose an extended language of tactics which support the derivation of formally verified theorems in the spirit of the logic programming paradigm.
Our setup, is based on the HOL Light theorem prover, in which we extend the currently available tactics mechanism with three basic features: (i) the explicit use of meta-variables, (ii) the ability to backtrack during the proof search, (iii) a layer of tools and facilities to interface with the underlying proof mechanism.
The basic building block of our framework are ML procedures that we call solvers, which are a generalization of HOL tactics and are – as well as tactics – meant to be used compositionally to define arbitrarily complex proof search strategies.
We say that our approach is semi-certified because
- on one hand, the produced solutions are formally proved theorems, hence their validity is guaranteed by construction;
- on the other hand, the completeness of the search procedure cannot be enforced in our framework and consequently has to be ensured by a meta-reasoning.
At the present stage, our implementation M. Maggesi and M. Nocentini. Kanren Light, 2018. URL https://github.com/massimo-nocentini/kanren-light is intended to be a test bed for experiments and further investigation on this reasoning paradigm.
6.3A simple example#
To give the flavor of our framework, we show how to perform simple computations on lists.
Consider first the problem of computing the concatenation of two lists
[1; 2] and [3]. One natural way to approach this
problem is by using rewriting. In HOL Light, this can be done by using
conversions with the command
# REWRITE_CONV [APPEND] `APPEND [1;2] [3]`;;where the theorem
# APPEND;;
val it : thm =
|- (!l. APPEND [] l = l) /\
(!h t l. APPEND (h :: t) l = h :: APPEND t l)gives the recursive equations for the operator APPEND.
Our implementation allows us to address the same problem from a logical point of view. We start by proving two theorems
# APPEND_NIL;;
val it : thm = |- !l. APPEND [] l = l
# APPEND_CONS;;
val it : thm =
|- !x xs ys zs. APPEND xs ys = zs
==> APPEND (x :: xs) ys = x :: zsthat gives the logical rules that characterize the APPEND
operator. Then we define a solver
let APPEND_SLV : solver =
REPEAT_SLV (CONCAT_SLV (ACCEPT_SLV APPEND_NIL)
(RULE_SLV APPEND_CONS));;which implements the most obvious strategy for proving a relation of
the form `APPEND x y = z` by structural analysis on the list
`x`. The precise meaning of the above code will be clear later
in this note; however, this can be seen as the direct translation of
the Prolog program
append([],X,X).
append([X|Xs],Ys,[X|Zs]) :- append(Xs,Ys,Zs).Then, the problem of concatenating the two lists is described by the term
`??x. APPEND [1;2] [3] = x`where the binder `(??)` is a syntactic variant of the usual
existential quantifier `(?)`, which introduces the
meta-variables of the query.
The following command
list_of_stream
(solve APPEND_SLV
`??x. APPEND [1; 2] [3] = x`);;runs the search process where the solve function starts the
proof search and produces a stream (i.e., a lazy list) of
solutions and the outermost list_of_stream transform the
stream into a list.
The output of the previous command is a single solution which is
represented by a pair where the first element is the instantiation for
the meta-variable `x` and the second element is a HOL theorem
val it : (term list * thm) list =
[([`x = [1; 2; 3]`], |- APPEND [1; 2] [3] = [1; 2; 3])]Now comes the interesting part: as in logic programs, our search
strategy (i.e., the APPEND_SLV solver) can be used for backward
reasoning.
Consider the variation of the above problem where we want to enumerate
all possible splits of the list [1; 2; 3]. This can be done by
simply changing the goal term in the previous query:
# list_of_stream
(solve APPEND_SLV
`??x y. APPEND x y = [1;2;3]`);;
val it : (term list * thm) list =
[([`x = []`; `y = [1; 2; 3]`],
|- APPEND [] [1; 2; 3] = [1; 2; 3]);
([`x = [1]`; `y = [2; 3]`],
|- APPEND [1] [2; 3] = [1; 2; 3]);
([`x = [1; 2]`; `y = [3]`],
|- APPEND [1; 2] [3] = [1; 2; 3]);
([`x = [1; 2; 3]`; `y = []`],
|- APPEND [1; 2; 3] [] = [1; 2; 3])]6.4A library of solvers#
Our framework is based on ML procedures called solvers. Solvers
generalizes classical HOL tactics in two ways, (i) they facilitate the
manipulation of meta-variables in the goal and (ii) they allows us to backtrack
during the proof search. We observe that the tactics mechanism currently
implemented in HOL Light already provides basic support for meta-variables in
goals; however, it seems to be used only internally in the implementation of
the intuitionistic tautology prover ITAUT_TAC.
We provide a library of basic solvers with the convention that their names end
in _SLV as in REFL_SLV, for instance.
Every HOL tactic can be “promoted” into a solver using the ML function
TACTIC_SLV : tactic -> solverA partial list of solvers approximately corresponding to classical HOL
tactics are ACCEPT_SLV, NO_SLV, REFL_SLV,
RULE_SLV (corresponding to MATCH_MP_TAC).
Notice that these solvers are different from their corresponding tactics because either
- use the stream mechanism instead of OCaml exceptions to handle the control flow; or
- perform some kind of unification.
For (1), a very basic example is the solver NO_SLV which,
instead of raising an exception, it returns the empty stream of
solutions.
One example of (2) is the REFL_SLV solver: when it is applied
to the goal
?- x + 1 = 1 + xwhere x is a meta-variable, closes the goal by augmenting the
instantiation with the substitution 1/x and
producing the theorem |- 1 + 1 = 1 + 1. Observe that the
corresponding REFL_TAC fails in this case.
As for tactics, we have a collection of higher-order solvers. Some of
them, are the analogous of the corresponding tacticals:
ASSUM_LIST_SLV,
CHANGED_SLV,
EVERY_SLV,
MAP_EVERY_SLV,
POP_ASSUM_LIST_SLV,
POP_ASSUM_SLV,
REPEAT_SLV,
THENL_SLV,
THEN_SLV,
TRY_SLV,
UNDISCH_THEN_SLV.
Given two solvers and the solver combinator
CONCAT_SLV make a new solver that collect sequentially all
solutions of followed by all solutions of . This is the
most basic construction for introducing backtracking into the proof
strategy.
From CONCAT_SLV, a number of derived combinators are defined to
capture the most common enumeration patterns, here
we give a brief list of those combinators without an explicit
description. However, we hope that the reader can guess the actual
behaviour from both their name and their ML type:
COLLECT_SLV : solver list -> solver
MAP_COLLECT_SLV : ('a->solver) -> 'a list -> solver
COLLECT_ASSUM_SLV : thm_solver -> solver
COLLECT_X_ASSUM_SLV : thm_solver -> solverSolvers can be used interactively. Typically, we can start a new goal
with the command gg and execute solvers with ee. The
command bb restore the previous proof state and pp
prints the current goal state. The stream of results is produced by
a call to top_thms().
Here is an example of interaction. We first introduce the goal,
notice the use of the binder (??) for the meta-variable x:
# gg `??x. 2 + 2 = x`;;
val it : mgoalstack =
`2 + 2 = x`one possible solution is by using reflexivity, closing the proof
# ee REFL_SLV;;
val it : mgoalstack =we can now form the resulting theorem
# list_of_stream(top_thms());;
val it : thm list = [|- 2 + 2 = 2 + 2]Now, if one want to find a different solution, we can restore the initial state
# bb();;
val it : mgoalstack =
`2 + 2 = x`then we use a different solver that allows us to unify with the
equation |- 2 + 2 = 4
# ee (ACCEPT_SLV(ARITH_RULE `2 + 2 = 4`));;
val it : mgoalstack =and again, we take the resulting theorem
# list_of_stream(top_thms());;
val it : thm list = [|- 2 + 2 = 4]Finally, we can change the proof strategy to find both solutions by using backtracking
# bb();;
val it : mgoalstack =
`2 + 2 = x`
# ee (CONCAT_SLV REFL_SLV (ACCEPT_SLV(ARITH_RULE `2 + 2 = 4`)));;
val it : mgoalstack =
# list_of_stream(top_thms());;
val it : thm list = [|- 2 + 2 = 2 + 2; |- 2 + 2 = 4]The function
solve : solver -> term -> (term list * thm) streamruns the proof search non interactively and produces a list of solutions as already shown in Section 6.3. In this last case it would be
# list_of_stream
(solve (CONCAT_SLV REFL_SLV (ACCEPT_SLV(ARITH_RULE `2 + 2 = 4`)))
`??x. 2 + 2 = x`);;
val it : (term list * thm) list =
[([`x = 2 + 2`], |- 2 + 2 = 2 + 2);
([`x = 4`], |- 2 + 2 = 4)]6.5Case study: Evaluation for a lisp-like language#
The material in this section is strongly inspired from the ingenious work of Byrd, Holk and Friedman about the miniKanren system W. E. Byrd, E. Holk, and D. P. Friedman. miniKanren, Live and Untagged: Quine Generation via Relational Interpreters (Programming Pearl). In Proceedings of the 2012 Annual Workshop on Scheme and Functional Programming, Scheme ’12, pages 8–29, New York, NY, USA, 2012. ACM. ISBN 978-1-4503-1895-2. doi: 10.1145/2661103.2661105. URL http://doi.acm.org/10.1145/2661103.2661105, where the authors work with the semantics of the Scheme programming language. Here, we target a lisp-like language, implemented as an object language inside the HOL prover. Our language is substantially simpler than Scheme; in particular, it uses dynamic (instead of lexical) scope for variables. Nonetheless, we believe that this example can suffice to illustrate the general methodology.
First, we need to extend our HOL Light environment with an object
datatype sexp for encoding S-expressions.
let sexp_INDUCT,sexp_RECUR = define_type
"sexp = Symbol string
| List (sexp list)";;For instance the sexp (list a (quote b)) is represented as HOL
term with
`List [Symbol "list";
Symbol "a";
List [Symbol "quote";
Symbol "b"]]`This syntactic representation can be hard to read and gets quickly
cumbersome as the size of the terms grows. Hence, we also introduce a
notation for concrete sexp terms, which is activated by the syntactic
pattern '(…). For instance, the above example
is written in the HOL concrete syntax for terms as
`'(list a (quote b))`With this setup, we can easily specify the evaluation rules for our
minimal lisp-like language. This is an inductive predicate with rules
for: (i) quoted expressions; (ii) variables; (iii) lambda
abstractions; (iv) lists; (v) unary applications. We define a ternary
predicate `EVAL e x y`, where
is a variable environment expressed as associative list, is the
input program and is the result of the evaluation.
let EVAL_RULES,EVAL_INDUCT,EVAL_CASES = new_inductive_definition
`(!e q. EVAL e (List [Symbol "quote"; q]) q) /\
(!e a x. RELASSOC a e x ==> EVAL e (Symbol a) x) /\
(!e l. EVAL e (List (CONS (Symbol "lambda") l))
(List (CONS (Symbol "lambda") l))) /\
(!e l l'. ALL2 (EVAL e) l l'
==> EVAL e (List (CONS (Symbol "list") l)) (List l')) /\
(!e f x x' v b y.
EVAL e f (List [Symbol "lambda"; List[Symbol v]; b]) /\
EVAL e x x' /\ EVAL (CONS (x',v) e) b y
==> EVAL e (List [f; x]) y)`;;We now use our framework for running a certified evaluation process for this language. First, we define a solver for a single step of computation.
let STEP_SLV : solver =
COLLECT_SLV
[CONJ_SLV;
ACCEPT_SLV EVAL_QUOTED;
THEN_SLV (RULE_SLV EVAL_SYMB) RELASSOC_SLV;
ACCEPT_SLV EVAL_LAMBDA;
RULE_SLV EVAL_LIST;
RULE_SLV EVAL_APP;
ACCEPT_SLV ALL2_NIL;
RULE_SLV ALL2_CONS];;In the above code, we collect the solutions of several different
solvers. Other than the five rules of the EVAL predicate, we
include specific solvers for conjunctions and for the two predicates
REL_ASSOC and ALL2.
The top-level recursive solver for the whole evaluation predicate is now easy to define:
let rec EVAL_SLV : solver =
fun g -> CONCAT_SLV ALL_SLV (THEN_SLV STEP_SLV EVAL_SLV) g;;Let us make a simple test. The evaluation of the expression
((lambda (x) (list x x x)) (list))can be obtained as follows:
# get (solve EVAL_SLV
`??ret. EVAL []
'((lambda (x) (list x x x)) (list))
ret`);;
val it : term list * thm =
([`ret = '(() () ())`],
|- EVAL [] '((lambda (x) (list x x x)) (list)) '(() () ()))Again, we can use the declarative nature of logic programs to run the
computation backwards. For instance, one intriguing exercise is the
generation of quine programs, that is, programs that evaluates to
themselves. In our formalization, they are those terms satisfying
the relation `EVAL [] q q`. The following command
computes the first two quines found by our solver.
# let sols = solve EVAL_SLV `??q. EVAL [] q q`);;
# take 2 sols;;
val it : (term list * thm) list =
[([`q = List (Symbol "lambda" :: _3149670)`],
|- EVAL [] (List (Symbol "lambda" :: _3149670))
(List (Symbol "lambda" :: _3149670)));
([`q =
List
[List
[Symbol "lambda"; List [Symbol _3220800];
List [Symbol "list"; Symbol _3220800; Symbol _3220800]];
List
[Symbol "lambda"; List [Symbol _3220800];
List [Symbol "list"; Symbol _3220800; Symbol _3220800]]]`],
|- EVAL []
(List
[List
[Symbol "lambda"; List [Symbol _3220800];
List [Symbol "list"; Symbol _3220800; Symbol _3220800]];
List
[Symbol "lambda"; List [Symbol _3220800];
List [Symbol "list"; Symbol _3220800; Symbol _3220800]]])
(List
[List
[Symbol "lambda"; List [Symbol _3220800];
List [Symbol "list"; Symbol _3220800; Symbol _3220800]];
List
[Symbol "lambda"; List [Symbol _3220800];
List [Symbol "list"; Symbol _3220800; Symbol _3220800]]]))]One can easily observe that any lambda expression is trivially a quine for our language. This is indeed the first solution found by our search:
([`q = List (Symbol "lambda" :: _3149670)`],
|- EVAL []
(List (Symbol "lambda" :: _3149670))
(List (Symbol "lambda" :: _3149670)))The second solution is more interesting. Unfortunately it is
presented in a form that is hard to decipher. A simple trick can help
us to present this term as a concrete sexp term: it is enough to
replace the HOL generated variable (`_3149670`) with a concrete
string. This can be done by an ad hoc substitution.
# let [_; i2,s2] = take 2 sols;;
# vsubst [`"x"`,hd (frees (rand (hd i2)))] (hd i2);;
val it : term =
`q = '((lambda (x) (list x x)) (lambda (x) (list x x)))`If we take one more solution from sols stream, we get a new
quine, which, interestingly enough, is precisely the one obtained in
W. E. Byrd, E. Holk, and D. P. Friedman. miniKanren, Live and Untagged: Quine Generation via Relational Interpreters (Programming Pearl). In Proceedings of the 2012 Annual Workshop on Scheme and Functional Programming, Scheme ’12, pages 8–29, New York, NY, USA, 2012. ACM. ISBN 978-1-4503-1895-2. doi: 10.1145/2661103.2661105. URL http://doi.acm.org/10.1145/2661103.2661105.
val it : term =
`q =
'((quote (lambda (x) (list x (list (quote quote) x))))
(quote (quote (lambda (x) (list x (list (quote quote) x))))))`Conclusions#
We presented a rudimentary framework implemented on top of the HOL Light theorem prover that enables a logic programming paradigm for proof searching. More specifically, it facilitates the use of meta-variables in HOL goals and permits backtracking during the proof construction.
It would be interesting to enhance our framework with more features:
- Implement higher-order unification such as Miller’s higher-order patterns, so that our system can enable higher-order logic programming in the style of Prolog.
- Support constraint logic programming, e.g., by adapting the data structure that represent goals.
Despite the simplicity of the present implementation, we have already shown the implementation of some paradigmatic examples of logic-oriented proof strategies. In the code base, some further examples are included concerning a quicksort implementation and a simple example of a logical puzzle.